I am calling a Python function several times and it returns a list with either one of the following:
1) single entry
2) multiple entry
3)blank list
For example:
a=['aaaaa']
b=['aaaaa', 'bbbbb', 'ccccc']
c=['aaaaa']
d=['ppppp', 'aaaaa']
e=['aaaaa', 'uuuuu']
Now, I want to find the common string in all the lists. I can do it as follows for TWO lists:
intercept_list=[val for val in a if val in b]
Is it possible to do it for multiple list in one go? Also supposing list "e" returned an empty list, I just want to ignore it.
Thank you
You can use intersection()
:
>>> set(a).intersection(b, c, d, e)
set(['aaaaa'])
You can use list()
to convert this back to a list:
result = list(set(a).intersection(b, c, d, e))
How about:
set.intersection(*(set(s) for s in list_of_lists if s))
For example:
>>> a=['aaaaa']
>>> b=['aaaaa', 'bbbbb', 'ccccc']
>>> c=['aaaaa']
>>> d=['ppppp', 'aaaaa']
>>> e=['aaaaa', 'uuuuu']
>>> f=[]
>>> list_of_lists = [a,b,c,d,e,f]
>>> set.intersection(*(set(s) for s in list_of_lists if s))
set(['aaaaa'])
A more generic implementation, counts the number of occurrence of the elements and verify if the count matches the list count
>>> def find_common(*args):
from collections import Counter
from itertools import takewhile, imap
from operator import itemgetter
count = sum(1 for e in args if e)
args = chain.from_iterable(args)
result = map(itemgetter(0),
takewhile(lambda e: e[-1] == count,
Counter(args).most_common()))
return result
>>> find_common(a,b,c,d,e)
['aaaaa']
>>> f = []
>>> find_common(a,b,c,d,e, f)
['aaaaa']
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.