筛选字符串中包含N个数字的列表元素

2024-06-15 08:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是代码返回一个空列表。有什么办法吗?你知道吗


Tags: 数据代码in列表data交易hsreactor
2条回答

似乎你在尝试应用正则表达式模式。您可以使用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}'

由于这是最初标记的熊猫,这里有一个熊猫解决方案:

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

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

不使用正则表达式也可以这样做,如下所示:

trade_data = ['84 Nuclear Reactor',
  '8401 Nuclear Reactor:Fuel Elem',
  '840120 Isotopic Separation Machinery',
  '8401200000 Isotopic Separation Machinery, Apparatus And Parts']
filtered_list = [i for i in trade_data if len([j for j in i if j.isdigit()])==10]
print(filtered_list) #prints ['8401200000 Isotopic Separation Machinery, Apparatus And Parts']

相关问题 更多 >