regex - 使用列表跳过字典中的数字/单词组合
问题描述
我有一个清单e
e = ['s', 'mm', 'ng']
和一个字典d
d = {'A1': ['Tomas',
'john',
'2s',
'Douglas',
'20ng'],
'B1': ['Tomm',
'3mm',
'Sterling',
'hey']}
我的目标是只跳过d
带有数字和元素的名称e
。
例如,2s
fromd
将被跳过,因为它有一个数字和一个来自 list2
的元素。s
e
我试过以下
r = {}
for k, v in d.items():
r[k] = [s for s in v if not any(s.endswith(val) for val in e)]
我得到
{'A1': ['john'], 'B1': ['hey']}
s
我拥有的代码是删除以例如结尾的元素'Tomas'
我想要的输出是以下内容,其中仅e
删除了数字+元素,例如3mm
{'A1': ['Tomas', 'john', 'Douglas'], 'B1': ['Tomm', 'Sterling', 'hey']}
如何更改代码以获得所需的输出?
解决方案
也许,这可能接近你的想法,
import re
e = ['s', 'mm', 'ng']
d = {'A1': ['Tomas',
'john',
'2s',
'Douglas',
'20ng'],
'B1': ['Tomm',
'3mm',
'Sterling',
'hey']}
r = {}
for k, v in d.items():
r[k] = [s for s in v if not any(re.match(r'^[0-9]', s) for val in e)]
print(r)
输出
{'A1':['Tomas','john','Douglas'],'B1':['Tomm','Sterling','嘿']}
在这里,我们假设那些以数字开头的那些是不受欢迎的,并找到那些使用,
re.match(r'^[0-9]', s)
并将其纳入if not
您在列表理解中已有的陈述中。