Find similar values in a list of lists
Question:
I know this question is asked a lot, but they are all used for different things.
What I want to happen:
#python 3.9
list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
matches = ["sand", "water"]
Is there a way to find matches this way?
Answers:
Convert the lists into sets and take their intersection. You can do this across an arbitrarily long list of sets in a single line with functools.reduce
:
>>> my_list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
>>> import functools
>>> functools.reduce(set.intersection, map(set, my_list))
{'grass', 'sand'}
I know this question is asked a lot, but they are all used for different things.
What I want to happen:
#python 3.9
list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
matches = ["sand", "water"]
Is there a way to find matches this way?
Convert the lists into sets and take their intersection. You can do this across an arbitrarily long list of sets in a single line with functools.reduce
:
>>> my_list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
>>> import functools
>>> functools.reduce(set.intersection, map(set, my_list))
{'grass', 'sand'}