子串过滤器列表元素由Python中的另一个列表 [英] Substring filter list elements by another list in Python

查看:89
本文介绍了子串过滤器列表元素由Python中的另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个看起来像这样的列表:

I have two lists looking like:

list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]

我想用list2的元素对list1进行子字符串过滤,并获得预期的输出,如下所示:

I want to substring filter list1 by elements of list2 and get expected output as follows:

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', ']']. 如何正确过滤?谢谢.

I get a result like this: ['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']']. How can I filter it correctly? Thanks.

与参考相关:

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

推荐答案

列表理解和any:

[i for i in list1 if any(i for j in list2 if str(j) in i)]

any检查list2的任何元素是否是要迭代的list1项(__contains__)的子字符串.

any to check if any element of list2 is a substring of the list1 item (__contains__) being iterated over.

示例:

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']

这篇关于子串过滤器列表元素由Python中的另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆