Filter list of lists in Python by element value

Question:

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.

Asked By: Vadim Katsemba

||

Answers:

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]]
Answered By: tobias_k

Using list comprehension which contains conditional statements.

lines = [
    [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]
]
requiredLine = [line for line in lines if line[0] == 2016 and line[1] == "Monday"]
print(requiredLine)
Answered By: Vyshak Puthusseri

I would separate the selection logic from the following filtering:

def func(x):
    return x[0] == '2016' and x[1] == "Monday"

list(filter(func, your_data))
Answered By: nikeros
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.