简体   繁体   English

按元素值过滤 Python 中的列表列表

[英]Filter list of lists in Python by element value

Suppose I have a list lines where every element is a list假设我有一个列表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]

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?例如,如果我想获取列表的第一个元素是 2016 并且第二个元素是星期一的所有元素,我将如何过滤掉列表? Think of this as filtering out a pandas dataframe by column values, but using a list of lists.可以将其视为按列值过滤 Pandas 数据框,但使用列表列表。

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]]
    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.使用包含条件语句的列表理解。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM