首页 > 解决方案 > Find last element of a list that fits a critera

问题描述

I have matrix (type list of lists) and I want to select only the last row that fits my critera. Specificly I have this matrix:

matrix = [
         [[0], whatever0],
         [[1], whatever1],
         [[1, 0], whatever10],
         [[1, 1], whatever11],
         [[1, 2], whatever12],
         [[1, 3], whatever13],
         [[1, 4], whatever14],
         ]

and I want to select only the LAST row i such that len(matrix[i][0]) == 1, so the answer should return [[1], whatever1].

Haven't found how to answer that specific question yet. Thank you.

标签: pythonlistselectelement

解决方案


You could do something like this:

matrix = [
    [[0], 'whatever0'],
    [[1], 'whatever1'],
    [[1, 0], 'whatever10'],
    [[1, 1], 'whatever11'],
    [[1, 2], 'whatever12'],
    [[1, 3], 'whatever13'],
    [[1, 4], 'whatever14'],
]

result = next((e for e in reversed(matrix) if len(e[0]) == 1), None)
print(result)

Output

[[1], 'whatever1']

Explanation

First iterate over the list backwards using reversed and return only the elements that have len(e[0]) == 1. Then with next get only the first result.


推荐阅读