python - 有没有更有效的方法来遍历字典列表?
问题描述
我正在尝试遍历字典列表,并只保留那些在其yearID
键中具有年份值的字典。本质上,列表 ( statistics
) 是棒球统计数据,每一行(字典)是球员一年中的统计数据。
这段代码似乎工作得很好(对于非常小的字典列表),但是一旦列表的大小超过 40 或 50,Thonny 就会崩溃:
def filter_by_year(statistics, year, yearid):
nlist = []
for dicts in statistics:
if str(dicts[yearid]) == str(year):
nlist.append(dicts)
return nlist
解决方案
取决于您所说的“高效”是什么意思。您的代码应该适用于大量字典,所以我假设您的意思是在编写代码方面高效。
在这种情况下,nlist
可以简化为一个简单的列表推导:
[dicts for dicts in statistics if str(dicts[yearid]) == str(year)]
推荐阅读
- neuroscience - 如何修复未创建 template_4D_GM 文件的 fslvbm_2_template 中的错误
- python - 根据从列表中选择的项目过滤掉框架
- assembly - 试图在大会中打印一个星形三角形
- sql - 在 c 中内连接 a 和 b
- java - 使用 java 的 AWS Kinesis Lambda 转换 - 未返回一个或多个记录 ID
- java - JPA Repository & Spring Security - 更新对象使密码无效
- java - 当两个变量都在android studio中浮动时出现ClassCastException
- javascript - jQuery 切换类无法正常工作
- laravel - 在 laravel 中加入 find_in_set
- python - Add column with closest vaues to PySpark Dataframe