Python中另一个列表的子字符串过滤列表元素

2023-12-24

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

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中的另一个字符串列表来过滤子字符串列表? https://stackoverflow.com/questions/46028725/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 item (__contains__) 被迭代。

Example:

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']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中另一个列表的子字符串过滤列表元素 的相关文章

随机推荐