【问题标题】:I can't iterate through duplicate values in a list我无法遍历列表中的重复值
【发布时间】:2021-06-30 11:24:33
【问题描述】:

问题在于我的列表年份,如您所见,有些值重复,如 1932、1933、1961...:

years = [1924, 1928, 1932, 1932, 1933, 1933, 1935, 1938, 1953, 1955, 1961, 1961, 1967, 1969, 1971, 1977, 1979, 1980, 1988, 1989, 1992, 1998, 2003, 2004, 2005, 2005, 2005, 2005, 2007, 2007, 2016, 2017, 2017, 2018]

所以我的职责是创建一个函数来遍历我的所有列表(所有列表都是 len 34),但我的输出只返回字典,其中只有一个重复年份,所以我的结果输出是 26 len 而不是 34

def dictionary_maker2(names, months, years, max_sustained_winds, areas_affected, list_update_damage, deaths):
    for n in range(len(years)):
        hurricanes_year[years[n]] = {'Names': names[n], 'Month': months[n], 'Year': years[n],
                                     'Max Sustained Wind': max_sustained_winds[n], 'Areas Affected': areas_affected[n],
                                     'Damage': list_update_damage[n], 'Deaths': deaths[n]}

如果我没有使用正确的方式在 stackoverflow 中提问,请告诉我,这是我在这里的第一个问题。

【问题讨论】:

  • 字典不能有重复的键。
  • 只是为了澄清@Selcuk 提到的内容,因为字典不能有重复的键,当访问您已经访问过的年份值并在上一次迭代中向字典添加值时,它将覆盖关联的当前值那一年用新的{'Names': '', ...}字典

标签: python list dictionary for-loop duplicates


【解决方案1】:

python 字典不能有重复的键,所以迭代中具有相同年份的最后一项会覆盖现有值。在这种情况下,您可以使用defaultdict

from collections import defaultdict
hurricanes_year = defaultdict(list)
def dictionary_maker2(names, months, years, max_sustained_winds, areas_affected, list_update_damage, deaths):
    for n in range(len(years)):
        hurricanes_year[years[n]].append({'Names': names[n], 'Month': months[n], 'Year': years[n],
                             'Max Sustained Wind': max_sustained_winds[n], 'Areas Affected': areas_affected[n],
                            'Damage': list_update_damage[n], 'Deaths': deaths[n]})

如果您想使用所有存储值遍历所有年份

for hurricanes in hurricanes_year:
    for hurricane in hurricanes:
        print(hurricane)

【讨论】:

    【解决方案2】:

    正如上面评论中提到的,我认为您不能将重复的年份存储为与每年关联的子词典的字典,因为每年只能存储一个飓风数据。要每年存储多个飓风数据,我认为您应该将hurricanes_year 设置为具有与包含当年飓风数据(字典)列表的列表(而不是字典)关联的年份的字典

    def dictionary_maker2(names, months, years, max_sustained_winds, areas_affected, list_update_damage, deaths):
        for n in range(len(years)):
            # Check if years[n] not exists in dictionary, if not then initialize empty list
            if years[n] not in hurricanes_year:
                hurricanes_year[years[n]] = []
            # Append hurricane data to the list associate with years[n]
            hurricanes_year[years[n]].append({'Names': names[n], 'Month': months[n], 'Year': years[n],
                                              'Max Sustained Wind': max_sustained_winds[n], 'Areas Affected': areas_affected[n],
                                              'Damage': list_update_damage[n], 'Deaths': deaths[n]})
    

    【讨论】:

      【解决方案3】:

      确实,dict,作为 hash-table 不能为同一个键保存多个值。

      要解决此问题,您可以尝试在字典中存储每年的列表或记录以及 append() 值而不是替换。

      {<year>: [{<field>: <value>, ...}, ...], ...}
      

      仅供参考:

      • 您可以使用zip() 将单独的值列表合并到单个元组列表中。
      • 元组可以以相同的方式与字典键组合,这样我们就可以构建字典而不用命名每个字段

      这可能有助于简化您的表达方式。例如:

      FIELD_NAMES = [
          'name', 
          'month', 
          'year', 
          'max_sustained_wind', 
          'area_affected', 
          'list_update_damage', 
          'deaths',
      ]
      
      def columns_to_recors(*columns):
          # translate list of columns to a generator of dicts
          # like {<field>: <value>}
          return (dict(zip(FIELD_NAMES, values)) for values in zip(*columns))
          
      
      def group_by_year(records):
          res = {}
          for rec in records:
              year = rec['year']
              group = res.setdefault(year, [])
              group.append(rec)
          return res
      
      def print_groups(groups):
          print('Year\tRecords')
          for year, records in sorted(groups.items()):
              print(f'{year}\t{records}')
      
      records = columns_to_records(*columns) # or (year, ..., smth_else)
      groups = group_by_year(records) # {<year>: [{...}, {...}]}
      print_groups(groups) 
      

      【讨论】:

        【解决方案4】:

        我找到了解决方案。诀窍在于 if-else 语句。所以,如果我的年份重复,我会将我的值附加到同一个键中。所以我的最终输出将类似于 '1928key': [{1928values}], '1932key': [{1932values, 1932values}]

        def create_year_dictionary(hurricanes):
        hurricanes_by_year= dict()
        for i in hurricanes:
            current_year = hurricanes[i]['Year']
            current_cane = hurricanes[i]
            if current_year not in hurricanes_by_year:
                hurricanes_by_year[current_year] = [current_cane]
            else:
                hurricanes_by_year[current_year].append(current_cane)
        return hurricanes_by_year
        

        打印(create_year_dictionary(hurricanes))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-06
          • 2019-06-14
          • 2023-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多