Python - 在三个列表中查找相同的元素(忽略空列表)

时间:2015-11-27 04:06:10

标签: python

如果有任何方法可以找到三个列表的共同元素,而忽略了三个列表中的空列表,那么我很想知道。 例如,我知道:

a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = ['d']
>>> set(a).intersection(b, v)
    {'d'}

但我想知道是否有办法做到这一点:

a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = []
>>> comparison_method(a, b, v)
    {'a', 'd'}

或者,如果3个列表中有2个为空,则只返回不是的列表。

3 个答案:

答案 0 :(得分:4)

使用过滤器然后设置交集:

set.intersection(*map(set,filter(None, [a,[],[]])))

O / P:set(['a', 'c', 'b', 'd'])

set.intersection(*map(set,filter(None, [a,b,[]])))

O / P:set(['a', 'd'])

set.intersection(*map(set,filter(None, [a,b,v])))

O / P:set(['d'])

正如jme建议哪个是更好的解决方案

set.intersection(*(set(x) for x in [a, b, v] if x))

答案 1 :(得分:2)

只过滤掉len的所有列表(即长度不为零)并使用set-intersection -

>>>a = ['a', 'b', 'c', 'd']
>>>b = ['a', 'v', 'd', 'g']
>>>v=[]
>>>input_list = [a,v,b]
>>>result = reduce(set.intersection,map(set,filter(len,input_list)))
>>>set(['a', 'd'])

答案 2 :(得分:1)

当然,与this非常相似,但只是在运行intersection测试之前过滤掉空列表:

def comparison_method(*args):
    sets = [set(arg) for arg in args if arg]
    if not sets:
        return []
    result = sets[0]
    for s in sets[1:]:
        result = result.intersection(s)
    return result

a = ['a', 'b', 'c', 'd']
b = ['a', 'v', 'd', 'g']
v = []
>>> comparison_method(a, b, v)
    {'a', 'd'}