Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find similar values in a list of lists

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading