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