a = ['ava','olivia','hannah','olivia']
b = ['aa','ab','ac','av']
for i in a:
for j in b:
if j in i:
print (i)
#output: ava
for i in a:
if any(j in i for j in b):
print (i)
#output: ava
有2个列表包含一些元素,我想在每个列表中列出2个元素,每个列表中有1个元素。
还有更好的方法吗?
答案 0 :(得分:5)
这就够了:
print [word for word in a if any(part in word for part in b)]
无需使用filter
,map
或lambda
。
答案 1 :(得分:0)
不一定更好,但他们是oneliners:
a = ['ava','olivia','hannah','olivia']
b = ['aa','ab','ac','av']
result = filter(None, map(lambda x: x if any(map(lambda y: y in x, b)) else None, a))
print result
或:
result2 = filter(None, [x if y in x else None for x in a for y in b])
print result3
或:
result3 = filter(None, [x if any([y in x for y in b]) else None for x in a])
print result2