【问题标题】:Loop through Dictionary and add values遍历字典并添加值
【发布时间】:2018-01-11 19:02:25
【问题描述】:

我正在尝试为字典中的重复键添加值。我不确定为什么我的代码不起作用。

d = {'inds': [], 'vals': []}
d['inds'] = [0,   3,   7,   3,   3,   5, 1]
d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

我想在索引 3 和 0 处为不存在的索引获取一个添加值作为结果的列表:

desired_output=[1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0]

我的代码:我正在制作零列表并在循环中添加字典。

d = {'inds': [], 'vals': []}
d['inds'] = [0,   3,   7,   3,   3,   5, 1]
d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

length=len(d['inds'])

a=[0]*(length)

for key,val in d.items():
    a[key]= a[key] + d[val]

它抛出一个错误: TypeError: 列表索引必须是整数或切片,而不是 str

感谢您的帮助。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你在这里甚至不需要字典(但我会把它留在里面)。只需压缩索引和值并添加到您的归零列表中。您的结果列表的长度也不正确。使用索引的max 加一计算它:

    d = {}
    d['inds'] = [0,   3,   7,   3,   3,   5, 1]
    d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
    
    result = [0]*(max(d["inds"])+1)
    for a,b in zip(d['inds'],d['vals']):
        result[a] += b
    

    结果:

    [1.0, 7.0, 0, 11.0, 0, 6.0, 0, 3.0]
    

    【讨论】:

      【解决方案2】:
      for key, val in d.items():
      

      这会遍历d 顶层的项目:首先是key='inds'val=[0, 3, 7, 3, 3, 5, 1],然后是key='vals'val=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]。但是您正在寻找 key 来获取值 0、3、7、3 等,而 val1.02.03.0 等。

      要遍历d['inds'] 中的索引和d['vals'] 中的值,请使用zip。它将并行地从每个子列表中一次拉出一项。

      for key, val zip(d['inds'], d['vals']):
      

      【讨论】:

      • 非常感谢。这很好地解释了如何使用 zip() 逐个遍历字典元素。效果很好。作为一名 Python 新手,我今天学到了一些新东西。
      • @RomanPerekhrest 这非常非常复杂。 C++ 文化将其视为骄傲而非尴尬。太难看了。模板元编程是可憎的。编译速度很慢。 “未定义行为”的概念是一种诅咒。崩溃时没有堆栈跟踪。这不是优雅
      • @JohnKugelman,我希望你能更好地考虑纯 C 语言,它是高性能“东西”(特别是)的最佳选择
      • 我不喜欢 C。我们是好朋友。
      【解决方案3】:

      使用较短但效率不高的列表理解:

      d = {}
      d['inds'] = [0,   3,   7,   3,   3,   5, 1]
      d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
      new_d = [0 if i not in d['inds'] else dict(zip(d['inds'], d['vals']))[i] for i in range(max(d["inds"])+1)]
      

      输出:

      [1.0, 7.0, 0, 5.0, 0, 6.0, 0, 3.0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-21
        • 2015-08-07
        • 1970-01-01
        • 2015-09-27
        • 2011-01-16
        • 2018-11-21
        • 1970-01-01
        相关资源
        最近更新 更多