【问题标题】:Sum Values in a Dictionary w/ respect to the Key - Python 2.7字典中的值总和与键相关 - Python 2.7
【发布时间】:2013-11-20 18:26:12
【问题描述】:

我的字典Dict排列如下。每个键都与一个值列表相关联,其中每个值都是一个元组:

Dict = { 
    'key1': [('Red','Large',30),('Red','Medium',40),('Blue','Small',45)],
    'key2': [('Red','Large',35)],
    'key3': [('Yellow','Large',30),('Red','Medium',30)], 
}

然后我想在给定一个新键的情况下对整数(每个元组的索引 2)求和,在这种情况下为 Color。

生成的新字典应如下所示:

{
    'key1': [('Red', 70), ('Blue', 45)],
    'key2': [('Red', 35)],
    'key3': [('Yellow', 30), ('Red', 30)],
}

我将如何做到这一点?

我在想类似以下的事情,但我知道这在几个方面是错误的。

sum = 0
new_dict = {}
new_key = raw_input("Enter a new key to search on: ")
for k,v in Dict:
  if v[0] == new_key:
    sum = sum + v[2]
    new_dict[k].append(sum)
  else:
    sum = 0
    new_dict[k] = [sum]

【问题讨论】:

  • 对不起,错字。那应该是字典。我原来的字典。

标签: python python-2.7 dictionary


【解决方案1】:

使用 dict 理解生成新的输出:

{key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}

color 是搜索的关键字。

演示:

>>> Dict = {
...     'key1': [('Red','Large',30),('Red','Medium',40),('Blue','Small',45)],
...     'key2': [('Red','Large',35)],
...     'key3': [('Yellow','Large',30),('Red','Medium',30)], 
... }
>>> color = 'Red'
>>> {key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}
{'key3': ['Red', 30], 'key2': ['Red', 35], 'key1': ['Red', 70]}

要按颜色对所有值求和,请使用Counter() 对值求和:

from collections import defaultdict, Counter

new_dict = {}
for key, values in Dict.iteritems():
    counts = Counter()
    for color, _, count in values:
        counts[color] += count
    new_dict[key] = counts.items()

给出:

>>> new_dict = {}
>>> for key, values in Dict.iteritems():
...     counts = Counter()
...     for color, _, count in values:
...         counts[color] += count
...     new_dict[key] = counts.items()
... 
>>> new_dict
{'key3': [('Red', 30), ('Yellow', 30)], 'key2': [('Red', 35)], 'key1': [('Blue', 45), ('Red', 70)]}

【讨论】:

  • 谢谢。这真的很有帮助。如果我没有指定颜色,而只想对给定键具有相同颜色的所有内容求和怎么办?请查看我上面对预期结果的修改。
  • @brno792:第二个元素的输出没有意义;应该是[('Red', 35)],列表中的一个元组。
  • 对不起,错误地遗漏了元组。它现在固定了。那么如何在不指定颜色的情况下做到这一点呢?谢谢
  • 谢谢。我还有另一个小问题。所以我求和的金额实际上是作为字符串存储在我原来的字典中的,所以我不能 += 它们。如何将该值转换为浮点数或双精度数?在创建我的 new_dict 或更早时,我应该在我的代码中的哪个位置执行此操作?
  • @brno792:那就用counts[color] += float(value)吧。
猜你喜欢
  • 1970-01-01
  • 2017-06-13
  • 2010-10-24
  • 1970-01-01
  • 2012-05-23
  • 2021-02-08
  • 2012-07-26
  • 2022-08-18
  • 2019-08-18
相关资源
最近更新 更多