Reputation: 359
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
Upvotes: 1
Views: 1167
Reputation: 12672
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']
Upvotes: 2
Reputation: 17358
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'}
Upvotes: 5