簡體   English   中英

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

[英]Python - finding same elements in three lists (ignoring empty list)

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

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個為空,則只返回不是的列表。

使用過濾器然后設置交集:

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))

只過濾掉所有具有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'])

當然,非常類似於 ,但只是在運行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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM