我有矩阵(列表的类型列表),我只想选择适合我的critera的最后一行。具体来说,我有这个矩阵:
matrix = [
[[0], whatever0],
[[1], whatever1],
[[1, 0], whatever10],
[[1, 1], whatever11],
[[1, 2], whatever12],
[[1, 3], whatever13],
[[1, 4], whatever14],
]
并且我只想选择last行i使得len(matrix [i] [0])== 1,所以答案应该返回[[1],whatever1]。
尚未找到如何回答该特定问题的方法。谢谢。
答案 0 :(得分:3)
您可以执行以下操作:
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)
输出
[[1], 'whatever1']
说明
首先使用reversed向后遍历列表,然后仅返回具有len(e[0]) == 1
的元素。然后使用next仅获得第一个结果。
答案 1 :(得分:2)
简单地向后迭代将是最有效的方法:
for i in range(len(matrix), -1, -1):
if len(matrix[i][0]) == 1:
print(matrix[i])
break
else:
print('No matching row found')
答案 2 :(得分:0)
检查this
>>> matrix = [
... [[0], "whatever0"],
... [[1], "whatever1"],
... [[1, 1], "whatever11"],
... [[1, 2], "whatever12"],
... [[1, 3], "whatever13"],
... [[1, 4], "whatever14"]
... ]
res=list(filter(lambda x: x[0][0]>0, matrix))[-1]
其中的res包含每个矩阵项目的第一个项目(合并的项目)的最后一个元素
... [[0],“ whatever0”],
... [[<< strong> 1 ],“ whatever1”],
... [[[ 1 ,1],“ whatever11”]
... [[<< strong> 1 ,2] **,“ whatever12”],
... [[<< strong> 1 ,3] **,“ whatever13”],
... [[<< strong> 1 ,4] **,“ whatever14”]