简体   繁体   English

元组中的和值(dict中的值)

[英]Sum values in tuple (values in dict)

I have a dictionary data that looks like that with sample values: 我有一个字典data ,看起来像样本值:

defaultdict(<type 'list'>, 
{(None, 2014): [(5, 1), (10, 2)], 
(u'Middle', 2014): [(6, 2), (11, 3)],
(u'SouthWest', 2015): [(7,3), (12, 4)]})

I get this from collections.defaultdict(list) because my keys have to be lists. 我从collections.defaultdict(list)得到这个,因为我的密钥必须是列表。

My goal is to get a new dictionary that will contain the sum values for every tuple with respect to their position in the tuple. 我的目标是获得一个新的字典,其中包含每个元组的总和值,以及它们在元组中的位置。

By running 通过运行

out = {k:(sum(tup[0] for tup in v),sum(tup[1] for tup in v)) for k,v in data.items()}

I get 我明白了

{(None, 2014): (15, 3),  (u'Middle', 2014): (17, 5), (u'SouthWest', 2015): (19, 7)}

However, I don't know in advance how many items will be in every tuple, so using the sum(tup[0] for tup in v) with hard-coded indices is not an option. 但是,我事先并不知道每个元组中有多少项,因此使用硬编码索引的sum(tup[0] for tup in v)不是一种选择。 I know, however, how many integers will be in the tuple. 但是,我知道元组中有多少个整数。 This value is an integer and I get this along with the data dict. 这个值是一个整数,我得到了data字典。 All tuples are always of the same length (in this example, of length 2). 所有元组的长度始终相同(在本例中,长度为2)。

How do I tell Python that I want the out dict to contain tuple of the size that matches the length I have to use? 我如何告诉Python我希望out dict包含与我必须使用的长度相匹配的大小的元组?

I think you want the built-in zip function : 我想你想要内置的zip功能

In [26]: {k: tuple(sum(x) for x in zip(*v)) for k, v in data.items()}
Out[26]: 
{('SouthWest', 2015): (19, 7),
 (None, 2014): (15, 3),
 ('Middle', 2014): (17, 5)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM