【问题标题】:How to add the values together in a key [duplicate]如何将值添加到键中[重复]
【发布时间】:2014-08-07 17:54:14
【问题描述】:

如果我有字典

example = {'cat' : 1, 'dog' : 2, 'cow' : 3, 'horse' : 4}

如何将这些值相加?

我试过了

count = 0
for x in example:
    example[x] += count
    print example

但这只会打印三遍示例。我该怎么做才能得到 10 作为答案?

【问题讨论】:

  • example 声明无效
  • 好吧,我的意思是字典哈哈,这只是一个失误

标签: python dictionary


【解决方案1】:

你很亲密:

example = {'cat' : 1, 'dog' : 2, 'cow' : 3, 'horse' : 4}
count = 0
for x in example:
    count += example[x]
print count

https://ideone.com/xHLkIg

Magnun Leno 和 iCodez 的答案更优雅(和 Python 风格)。

【讨论】:

    【解决方案2】:

    你想要的是这个:

    example = {'cat' : 1, 'dog' : 2, 'cow' : 3, 'horse' : 4}
    for x in example:
        count += example[x]
    print count
    

    或者:

    example = {'cat' : 1, 'dog' : 2, 'cow' : 3, 'horse' : 4}
    sum(example.values())
    

    【讨论】:

      【解决方案3】:

      您可以使用sumdict.itervalues(Python 3.x 中的dict.values):

      >>> example = {'cat' : 1, 'dog' : 2, 'cow' : 3, 'horse' : 4}
      >>> sum(example.itervalues())
      10
      >>>
      

      【讨论】:

      • dict.values 也出现在 Python 2 中
      • 是的,但它会创建一个不必要的列表。 dict.itervalues 但是在 Python 3.x 中返回类似 dict.values 的迭代器。
      猜你喜欢
      • 2016-04-08
      • 2014-04-13
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多