【问题标题】:Is there a more efficient way to iterate over a list of dictionaries?有没有更有效的方法来遍历字典列表?
【发布时间】:2019-09-30 20:37:47
【问题描述】:

我正在尝试遍历字典列表,并仅在其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

【问题讨论】:

  • 如果您需要,此代码可以工作,并且足够高效,可用于 100.000 - 1.000.000 个字典。
  • 为什么要比较年份的字符串表示而不是直接比较年份? dicts[yearid]==year。转换为字符串肯定需要很多时间。

标签: python list dictionary iteration


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    到目前为止提出的所有方法(prashant ranaZaid Afzalalec_aSteven Burnap >),你的 - 原来的 - 是最有效的。如果消除不必要的字符串转换,它会变得有点 3x

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        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
        

        【讨论】:

          【解决方案5】:

          filter 也可以是个好办法

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-11-20
            • 2018-12-12
            • 1970-01-01
            • 2021-11-12
            • 2017-02-03
            • 2019-11-23
            • 1970-01-01
            相关资源
            最近更新 更多