我有两个列表看起来像:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
我想通过list1
的元素子字符串过滤list2
并得到预期的输出,如下所示:
outcome = ['bj-100-cy', 'sh-200-pd']
做的时候:
list1 = str(list1)
list2 = str(list2)
outcome = [x for x in list2 if [y for y in list1 if x in y]]
我得到这样的结果:['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']']
。我该如何正确过滤?谢谢。
参考相关:
Is it possible to filter list of substrings by another list of strings in Python?
列表理解和any
:
[i for i in list1 if any(i for j in list2 if str(j) in i)]
any
检查list2
的任何元素是否是list1
项目(__contains__
)的子串被迭代。
例:
In [92]: list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
...: list2 = [100, 200]
...:
In [93]: [i for i in list1 if any(i for j in list2 if str(j) in i)]
Out[93]: ['bj-100-cy', 'sh-200-pd']
你可以使用any
:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
list2 = [str(x) for x in list2]
outcome = [s for s in list1 if any(x in s for x in list2)]
如果你给它的任何条件是any
,True
会返回True
。
list1 = str(list1)
list2 = str(list2)
您正在将列表转换为包含上述语句的字符串。因此,当您在for循环中进行迭代时,您将迭代每个字符,而不是每个字。
因此,您应该删除字符串转换,而是按如下方式执行列表推导。此外,在结果文件中,而不是检查list2中的单词是否在list1中,您正在检查相反的情况。所以你得到100和200作为列表2中的字符。
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
outcome = [x for x in list1 for y in list2 if str(y) in x]
你可以尝试这个:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
outcome = []
for item in list1:
if any(str(i) in item for i in list2):
outcome.append(item)
输出:
['bj-100-cy', 'sh-200-pd']
另一个替代列表理解:
>>> list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
>>> list2 = [100, 200]
>>> occur = [i for i in list1 for j in list2 if str(j) in i]
>>> occur
['bj-100-cy', 'sh-200-pd']
您可以使用内置的filter方法根据您的条件筛选列表。你的条件需要python in
运算符来搜索haystack ([100, 200])
中的needle([['bj-100-cy','bj-101-hd',...]])
。我们可以使用contains
方法来简化搜索语法。
码
from operator import contains
filter(lambda x: any(contains(x,str(y)) for y in list2), list1)
例
>>> list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
>>> list2 = [100, 200]
>>> for item in filter(lambda x: any(contains(x,str(y)) for y in list2), list1):
... print(item)
...
bj-100-cy
sh-200-pd
你可以使用正则表达式:
import re
list1 = ['bj-100-cy', 'bj-101-hd', 'sh-200-pd', 'sh-201-hp']
list2 = [100, 200]
pattern = re.compile('|'.join(map(str, list2)))
list(filter(lambda x: pattern.search(x), list1))
# ['bj-100-cy', 'sh-200-pd']