ahb*_*bon 4 python string list-comprehension list filter
我有两个列表,如下所示:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
Run Code Online (Sandbox Code Playgroud)
我想list1
按 的元素进行子字符串过滤list2
并获得预期输出,如下所示:
outcome = ['bj-100-cy', 'sh-200-pd']
Run Code Online (Sandbox Code Playgroud)
做时:
list1 = str(list1)
list2 = str(list2)
outcome = [x for x in list2 if [y for y in list1 if x in y]]
Run Code Online (Sandbox Code Playgroud)
我得到这样的结果:['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']']
。如何才能正确过滤呢?谢谢。
相关参考:
列表理解和any
:
[i for i in list1 if any(i for j in list2 if str(j) in i)]
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)