python - 从列表中提取字符串

标签 python string

我有一个列表:

my_list = ['A70-11370; reprint; rolled; 2000; 26.5 x 38.5',
 'A70-713; reprint; rolled; 1980; 26.5 x 38.5',
 'b70-7814; reprint; Style A; rolled; 1939; 22.5 x 34.5',
 'A70-7600; reprint; rolled; 1986; 26.5 x 38.5',
 'A70-6912; reprint; style C; rolled; 1977; 26.5 x 38.5',
 'A70-8692; reprint; regular; rolled; 1995; 26.5 x 38.5',
 'A70-2978; reprint; rolled; 1991; 26.5 x 38.5',
 'A70-4902; reprint; Style A; rolled; 1999; 26.5 x 38.5',
 'A70-6300; reprint; regular; rolled; 1983; 26.5 x 38.5',
 'MPW-6725; reprint; rolled; 1966; 26.5 x 38']

我想提取包含“x”的字符串(例如 26.5 x 38.5)。我试过:

string = [i if 'x' in i else np.nan for i in str(my_string).split(';')]

将 nan 放置在不满足条件的地方,但我只是在那里的一部分。有没有办法在有和没有 nan 占位符的情况下获取我想要的字符串?

最佳答案

你需要一个嵌套列表理解来获取列表中的每个子字符串。

[x for s in my_list for x in s.split('; ') if 'x' in x]

结果:

['26.5 x 38.5', '26.5 x 38.5', '22.5 x 34.5', '26.5 x 38.5', '26.5 x 38.5', '26.5 x 38.5', '26.5 x 38.5', '26.5 x 38.5', '26.5 x 38.5', '26.5 x 38']

使用 re 会更适合这种情况,因为仅使用 if 'x' in x 可能会返回不需要的结果:

p = re.compile("\d+\.\d+ x \d+\.\d+")
[m.group(0) for m in map(p.search, my_list) if m]

关于python - 从列表中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58369141/

相关文章:

python - 是否有标准的第 3 方 Python 缓存类?

python - 使用 Python 的 Eclipse - 难以选择 python 版本来创建 egg 文件

javascript - JavaScript 中的 new String ("x") 有什么意义?

java - 将字符串转换为整数 - 如果字符串无效,我应该返回什么

MySQL 输出十六进制字符串为 UTF-8

c++ - 在特定位置将 char 附加到 std::vector<string>

javascript - 向名为 'speak' 的原型(prototype)添加方法

python - a += b 与 a = a + b 不同

python - 如何使用 BeautifulSoup 获取 <tr> 中的特定 <td>

python - 使用嵌套 for 循环的反元音程序