0
    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 个包含一些元素的列表,我想要每个列表 1 个元素中的每个列表 2 个元素。

有没有更好的获取方式?

4

2 回答 2

5

这就够了:

print [word for word in a if any(part in word for part in b)]

无需使用filter,maplambda.

于 2012-10-07T12:42:43.910 回答
0

不一定更好,但它们是单线:

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
于 2012-10-07T12:35:41.813 回答