python - 从 2 个字符串列表中获取一个列表
问题描述
对于这些列表:
a=['applepearstrawberry','applepearbanana','orangekiwiapple','xxxxxxxxxxx']
b=['apple','pear']
如何返回包含“apple”或“pear”的任何元素的列表。
期望的输出
c=['applepearstrawberry','applepearbanana','orangekiwiapple']
尝试的解决方案:
c=[]
for i in a:
if b[0] or b[1] in a:
c.append(i)
print(c)
谢谢
解决方案
使用any()
:
a = ["applepearstrawberry", "applepearbanana", "orangekiwiapple", "xxxxxxxxxxx"]
b = ["apple", "pear"]
out = [v for v in a if any(w in v for w in b)]
print(out)
印刷:
['applepearstrawberry', 'applepearbanana', 'orangekiwiapple']
推荐阅读
- javascript - Vue.js:根据文件扩展名将内容加载到 DOM
- arrays - ThisWorksheet 上的数组在 Sheet1 上不可用
- python - 查找和计算字符串中提到的单词(python 3)
- optimization - 有效使用英特尔编译器 SVML `__m128 _mm_sincos_ps ()`
- python - Python 3.6 IDLE、macOS 中的 TensorFlow 导入警告
- r - R 闪亮:runApp() 可以在浏览器中的“http://localhost:port/”而不是“http://127.0.0.1:port/”打开闪亮的应用程序吗?
- python - 如何使用带有 Python 的 Selenium Webdriver 通过它们的 ID 获取元素的标签?
- r - 在第一个结束字符实例之后执行 gsub,而不是继续到字符串结尾
- xamarin - 相对于外部绑定上下文,如何在 ListView 中设置绑定上下文?
- lambda - 过滤器函数pyspark中“or-ing”时的括号