Home > Enterprise >  Filter list of lists in Python by element value
Filter list of lists in Python by element value

Time:11-08

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.

CodePudding user response:

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]]

CodePudding user response:

    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)

Using list comprehension which contains conditional statements.

CodePudding user response:

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))
  • Related