简体   繁体   中英

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

I was wodnering if there was any way to find the common elements of three lists, whilst ignoring a list that is empty among the three. For example I know that:

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

but I was wondering if there was a way to do this:

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

Or if 2 out of 3 lists were empty, it would just return the list that wasn't.

Using filter and then set intersection:

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

As jme suggested which is a more better solution

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

Just filter out all the list that have len (ie length is not zero) and use 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'])

Sure, very similar to this , but just filter out the empty lists before running the intersection test:

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM