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

Filter list of lists in Python by element value

Suppose I have a list lines where every element is a list

['2015', 'Friday', 9.94, 0.0]
['2015', 'Tuesday', 10.54, 0.002615]
['2015', 'Wednesday', 9.86, -0.001531]
['2016', 'Monday', 10.41, 0.007841]
['2016', 'Thursday', 11.51, 0.006415]
['2017', 'Tuesday', 8.74, -0.003711]
['2017', 'Friday', 12.62, 0.008516]

How would I filter out the list if, for example, I wanted to get all the elements where the first element of a list is 2016 and the second element is Monday? Think of this as filtering out a pandas dataframe by column values, but using a list of lists.

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 :

Just use a list comprehension with condition:

>>> [x for x in lst if x[0] == 2016 and x[1] == "Monday"]
[[2016, 'Monday', 10.41, 0.007841]]
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