我有一个列表,其中包含交易数据的 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/