简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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