[英]Filter list by sublist element match
I have the following doubly-nested list: 我有以下双重嵌套的列表:
records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]]
I want to filter this list according to where the 2nd element (by indexing) of the inner-most list equals 1. The result should look like this: 我想根据最内层列表的第二个元素(通过索引)等于1的位置来过滤此列表。结果应如下所示:
records
[[['Jack', 'male', 1]],[['Sally', 'female', 1]]]
I think some form of nested list comprehension with a conditional is probably what I need but I can't figure it out. 我认为某种形式的带有条件的嵌套列表理解可能是我需要的,但我无法弄清楚。
You can use a nested list comprehension: 您可以使用嵌套列表理解:
records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]]
final_records = [[i for i in b if i[-1] == 1] for b in records]
Output: 输出:
[[['Jack', 'male', 1]], [['Sally', 'female', 1]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.