python - 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', ']']
. 我怎样才能正确过滤它?谢谢。
参考相关:
解决方案
列表理解和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']
推荐阅读
- node.js - 在中间件文件中编码或清理请求正文
- java - Spring:使用@EntityScan 禁用自动实体发现
- javascript - 计算机在剪刀石头布 JavaScript 中选择不同的答案
- r - Creating a function to replace NAs from one data frame with values from another
- javascript - 滚动进度指示器不适用于 fullpage.js
- reactjs - React 中的悬念承诺何时执行?
- sql - case 语句中的多个条件重复表中的行
- azure - 如何使用 terraform.. 在 Azure 服务总线中创建创建多个主题和多个订阅?
- python - AWS Glue - 将 Json 响应从 GET(REST API) 请求转换为 DataFrame/DynamicFramce 并将其存储在 s3 存储桶中
- reactjs - 在 React Native 应用程序中使用 firebase 时遇到一些困难 - 警告:遇到两个具有相同密钥的孩子