简体   繁体   中英

Python - Check if any item exists in all list of lists

I have a list of lists in Python (python3). Example:

list_of_lists = [[vendor1, vendor2],
                 [vendor2, vendor5, vendor10],
                 [vendor1, vendor2, vendor7]]

What I'm trying to do is find out if there is an item that is in ALL lists in the list of lists. Most of the examples I've come across the user has known what value to search for in their list of lists, hence me asking a separate question on here, as I don't have a starting value to search for. The result from the above list would return vendor2 since it shows up in all lists.

Any help/general "look in this direction" advice is appreciated. Thank you

Assuming all elements of the list_of_lists are strings. Using set and intersection concepts. Create a set for each sublist and do intersection on all of them

In [3]: list_of_lists = [["vendor1", "vendor2"],
   ...:                  ["vendor2", "vendor5", "vendor10"],
   ...:                  ["vendor1", "vendor2", "vendor7"]]

In [4]: set.intersection(*[set(x) for x in list_of_lists])
Out[4]: {'vendor2'}

Also could try reduce :

from functools import reduce

list_of_lists = [["vendor1", "vendor2"],
                 ["vendor2", "vendor5", "vendor10"],
                 ["vendor1", "vendor2", "vendor7"]]


result = list(reduce(lambda a, b: set(a) & set(b), list_of_lists))
# ['vendor2']

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