Python 有没有更有效的方法来迭代字典列表?

Python 有没有更有效的方法来迭代字典列表?,python,list,dictionary,iteration,Python,List,Dictionary,Iteration,我试图遍历字典列表,只保留那些在yearID键中有年份值的字典。基本上,列表(统计数据)是棒球统计数据,每一行(字典)是一年中球员的统计数据 这段代码似乎工作得很好(对于非常小的字典列表),但一旦列表的大小超过40或50,Thonny就会崩溃: def filter_by_year(statistics, year, yearid): nlist = [] for dicts in statistics: if str(dicts[yearid]) == str

我试图遍历字典列表,只保留那些在
yearID
键中有年份值的字典。基本上,列表(
统计数据
)是棒球统计数据,每一行(字典)是一年中球员的统计数据

这段代码似乎工作得很好(对于非常小的字典列表),但一旦列表的大小超过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

我不知道它是否更有效,但列表理解是更干净的代码:

return [dicts for dicts in statistics if str(dicts[yearid]) == str(year)]
这取决于你所说的“高效”是什么意思。你的代码应该可以很好地用于大量的字典,所以我假设你所说的“高效”是指编写的代码

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

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

过滤器也可以是一种好方法

def filter_by_year(statistics, year, yearid):
    nlist = list(filter (lambda dicts: str(dicts[yearid]) == str(year), statistics))
    return nlist

您可以使用生成器只获取年份,并保持字典索引的迭代

def filter_by_year(statistics, year, yearid):

    nlist = []

    for i, yearid_ in enumerate(dict[yearid] for dict in statistics): 
        if str(yearid_) == str(year):
            nlist.append(statistics[i])

    return nlist

在迄今为止提出的所有方法中(由prashant rana、Zaid Afzal、alec_a和Steven Burnap提出),你的方法——最初的方法——是最有效的。如果消除了对字符串的不必要转换,则速度会加快3倍

def filter_by_year(statistics, year, yearid): 
    nlist = [] 
    for dicts in statistics: 
        if dicts[yearid] == year: 
            nlist.append(dicts) 
    return nlist 

如果需要的话,这段代码对于100.000-1.000.000字典来说是有效的。为什么要比较年份的字符串表示形式而不是直接比较年份<代码>目录[yearid]==年份
。转换为字符串肯定要花很多时间。