python - 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.
解决方案
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.
推荐阅读
- typescript - 更新 typescript 后 typescript": "4.4.4" - 尝试 npm run build 时出错 - 类型 'Navigator' 上不存在属性 'msSaveOrOpenBlob'
- angular - 无法从 stackblitz 示例中重现 Angular 项目环境
- python - 比较两列并删除 row_pandas 上的重复项
- azure-functions - 无法在 Azure Functions App v3 中加载文件或程序集“Microsoft.Extensions.DependencyModel,版本 = 3.0.0.0”
- java - IntelliJ - 问题视图不显示任何编译错误,但强调类
- git - 在本地存储库中提交多个文件(包括我需要推送的文件)后,如何将特定文件推送到 GitLab?
- python - 如何在 Java 中调用 Python 脚本并将 ArrayList 传递给它进行处理?
- typescript - 测试依赖 Promise 的 React Native 功能组件
- c - Xcode 错误消息没有逻辑意义
- python - 如何确保我的代码继续循环,同时只接受来自用户输入的整数值?