首页 > 解决方案 > Python中另一个列表的子字符串过滤列表元素

问题描述

我有两个列表,如下所示:

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', ']']. 我怎样才能正确过滤它?谢谢。

参考相关:

是否可以通过 Python 中的另一个字符串列表过滤子字符串列表?

标签: pythonstringlistfilterlist-comprehension

解决方案


列表理解和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']

推荐阅读