Python 如何从其他列表中筛选列表
我有以下清单:Python 如何从其他列表中筛选列表,python,list,Python,List,我有以下清单: names = ['aet2000','ppt2000', 'xxx2001', 'ppt2001'] wanted_list = ['aet','xxx'] 我想做的是在名称中获取包含通缉名单中字符串的列表 我可以使用它,我手动将aet和xxx放入过滤器功能中 In [17]: filter(lambda x:'aet' in x or 'xxx' in x, names) Out[17]: ['aet2000', 'xxx2001'] 但是它没有使用列表通缉名单。我该怎么
names = ['aet2000','ppt2000', 'xxx2001', 'ppt2001']
wanted_list = ['aet','xxx']
我想做的是在名称中获取包含通缉名单中字符串的列表
我可以使用它,我手动将aet
和xxx
放入过滤器功能中
In [17]: filter(lambda x:'aet' in x or 'xxx' in x, names)
Out[17]: ['aet2000', 'xxx2001']
但是它没有使用列表通缉名单。我该怎么做?这是一个列表:
>>> [name for name in names if any(substring in name for substring in wanted_list)]
['aet2000', 'xxx2001']
正如DYZ所说,aet
或xxx
在x中是错误的,它将返回名称中的所有元素,我想这是您想要的:
names =['aet2000','ppt2000', 'xxx2001', 'ppt2001']
wanted_list = ['aet','xxx']
print filter(lambda x:'aet' in x or 'xxx' in x, names)
或者您可以尝试以下方法:
print [j for i in wanted_list for j in names if i in j]
顺便说一下,也许startswith
也可以这样做:
print [j for i in wanted_list for j in names if j.startswith(i)]
可以使用正则表达式提取字符串中要匹配的部分,并检查该部分是否在列表中
>>> import re
>>> names = ['aet2000','ppt2000', 'xxx2001', 'ppt2001']
>>> wanted_list = ['aet','xxx']
>>> [name for name in names if re.match(r'[^\d]+|^', name).group(0) in wanted_list]
['aet2000', 'xxx2001']
无论如何,'aet'或'xxx'在x
中是错误的,因为它在x
中的意思是('aet'或'xxx'),后者在x
中只是'aet'。您需要的是x中的“aet”或x中的“xxx”
。