首页 > 解决方案 > 从 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)

谢谢

标签: pythonstringlistlist-comprehension

解决方案


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

推荐阅读