首页 > 解决方案 > 有没有更有效的方法来遍历字典列表?

问题描述

我正在尝试遍历字典列表,并只保留那些在其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

标签: pythonlistdictionaryiteration

解决方案


取决于您所说的“高效”是什么意思。您的代码应该适用于大量字典,所以我假设您的意思是在编写代码方面高效。

在这种情况下,nlist可以简化为一个简单的列表推导:

[dicts for dicts in statistics if str(dicts[yearid]) == str(year)]

推荐阅读