对元组的元组和嵌套的dict进行求和 [英] Summing a tuple-of-tuples and a nested dict

查看:526
本文介绍了对元组的元组和嵌套的dict进行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据可以用两种不同的形式表示(出于历史原因,我不会进入)。第一个是元组 tuple s:

  t =(('a','x',3),
('a','f',1),
('b' r',23),
('b','e',3))

第二个为 dict of dict s:

  d = {'a':{'x':45,'f':4},
'b':{'r':34,'e' :45}}

相同的数据,我现在需要结合两个(并且必须保持元组元组形式而不是嵌套的dict形式),值 summed

 (('a','x',48),
('a','f' ,5),
('b','r',57),
('b','e',48))

看起来这是一个两步过程(将嵌套的dict转换为tuple的元组,然后对每个元组中的相应元组求和)。我努力超过第一部分,我缺少两个元组(我不喜欢我如何硬编码索引):

 在[1025]:def f(d):
for k,v in d.items():
yield(k,d [k] .keys在[1026]中:for i in f(d):
(b)[b]
print i
......:
('a','x',45)
('b','r',34)

什么是更好的方法?

解决方案

您可以使用 tuple()中的生成器表达式,通过循环遍历您的元组并将第三个项目与其在字典中的相对值相加:

 >>>对于i,j,k在t中的元组((i,j,k + d.get(i,{})。get(j,0) ),
('a','f',5),
('b','r',57),
('b','e'

请注意,使用 dict.get()方法是如果键在字典中不存在则返回0。



请注意,如果它没有任何区别,你有一个列表的元组或元组的元组,您可以使用列表解析而不是生成器表达式。因为列表推导在运行时更加优化,因为它不需要在生成器函数中调用诸如 next()等额外的方法来检索项目。 p>

I have data that can be represented in two different forms (for historical reasons that I won't go into). The first is a tuple of tuples:

t = (('a', 'x', 3), 
('a', 'f', 1), 
('b', 'r', 23), 
('b', 'e', 3))

And the second as a dict of dicts:

d = {'a' : {'x': 45, 'f' : 4},
     'b' : {'r' : 34, 'e' : 45}}

Same data, different representation. I now need to end up with a combination of the two (and must maintain the tuple-of-tuples form rather than the nested dict form), with the values summed. i.e.

(('a', 'x', 48), 
('a', 'f', 5), 
('b', 'r', 57), 
('b', 'e', 48))

It seems this is a two-step process (convert the nested dict to a tuple of tuples, then sum the corresponding tuples within each tuple). I'm struggling to get past the first part, I am missing two tuples (and I don't like how I have hardcoded the indexing either):

In [1025]: def f(d):
    for k, v in d.items():
        yield (k, d[k].keys()[0], d[k].values()[0])
   ......:         

In [1026]: for i in f(d):

    print i
   ......:     
('a', 'x', 45)
('b', 'r', 34)

What is a better way?

解决方案

You can use a generator expression within tuple(), by looping over your tuples and summing the third item with it's relative value in dictionary:

>>> tuple((i, j, k + d.get(i, {}).get(j, 0)) for i, j, k in t)
(('a', 'x', 48),
 ('a', 'f', 5),
 ('b', 'r', 57),
 ('b', 'e', 48))

Note that the advantage of using dict.get() method is that it returns 0 if the key doesn't exist in dictionary.

Note that if it doesn't make any difference for you to have a list of tuples or tuple of tuples, you can use a list comprehension instead of a generator expression. because list comprehension is more optimized in terms of runtime as it doesn't need to call extra methods like next() in a generator function in order to retrieve the items.

这篇关于对元组的元组和嵌套的dict进行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆