python - 过滤字符串中包含 N 位数字的列表元素

标签 python list

我有一个列表,其中包含交易数据的 HS 代码,如下所示

trade_data = ['84 Nuclear Reactor',
  '8401 Nuclear Reactor:Fuel Elem',
  '840120 Isotopic Separation Machinery',
  '8401200000 Isotopic Separation Machinery, Apparatus And Parts']

我想过滤此列表,以便该列表仅包含名称中有 10 位数字的项目,在本例中为“8401200000 同位素分离机械、仪器和零件”。

我试过了

filtered_list = [x for x in trade_data if "\d{10}" in x] 

但是代码返回一个空列表。有没有办法做到这一点?

最佳答案

您似乎正在尝试应用正则表达式模式。您可以使用 re.search:

import re
[x for x in trade_data if re.search(r"\d{10}", x)] 
# ['8401200000 Isotopic Separation Machinery, Apparatus And Parts']

或者,更好的是,预编译您的模式:

p = re.compile(r"\d{10}")
[x for x in trade_data if p.search(x)] 
# ['8401200000 Isotopic Separation Machinery, Apparatus And Parts']

Note
If you need to match digits at the start of the string, add the start-of-line anchor ^ to your pattern:

r'^\d{10}'

因为这最初被标记为 pandas,这里是一个 pandas 解决方案:

s = pd.Series(trade_data)
s[s.str.contains(r'^\d{10}')]

3    8401200000 Isotopic Separation Machinery, Appa...
dtype: object

关于python - 过滤字符串中包含 N 位数字的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54010788/

相关文章:

python - 使用要排除的索引列表进行索引

vb.net - 如何将值插入(字符串,列表(字符串))字典的列表部分?

python - 错误 : No module named staticfiles in django 1. 3.1 + python 2.6?怎么了

python - 如何根据类别将 Pandas 数据框行转换为列?

list - Lisp 列表中的不完整输出,# 给出的列表深度超过 4

linq - 有没有办法从某种类型的列表中创建属性值列表?

python - 将每个列表的元素与列表中的其他元素进行比较

python - Selenium WebDriver + Tor 作为 Stem 的代理?

c++ - 在 C++ 中切片 char 数组(python 到 c++)

python - 如何获取列表的最后一个元素?