在字典中迭代函数

时间:2017-02-04 18:01:25

标签: python dictionary

我是python中的新手,我在理解如何使用列表和词典方面遇到了问题。特别是,我无法解决这个问题:

给出以下字典:

A=[{'t':1, 'X':10, 'Y': 15},
   {'t':4, 'X':2500, 'Y': 3000},
   {'t':1, 'X':20, 'Y': 10},
   {'t':3, 'X':0.10, 'Y': 0.40},
   {'t':2, 'X':400, 'Y': 400},
   {'t':3, 'X':0.20, 'Y': 0.10},
]

我必须编写一个代码来创建一个新字典,以便对每个tXY进行求和。然后每个t必须只出现一次(按时间顺序排列),并且那些属于同一t的总和必须全部加在一起。输出应该是这样的:

B=[{'t':1, 'SUM':55},
   {'t':2, 'SUM':800},
   {'t':3, 'SUM':0.80},
   {'t':4, 'SUM':5500},
]

请有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

>>> A=[{'t':1, 'X':10, 'Y': 15},
...    {'t':4, 'X':2500, 'Y': 3000},
...    {'t':1, 'X':20, 'Y': 10},
...    {'t':3, 'X':0.10, 'Y': 0.40},
...    {'t':2, 'X':400, 'Y': 400},
...    {'t':3, 'X':0.20, 'Y': 0.10},
... ]
>>> my_dict = {}
>>> for d in A:
...     my_dict.update({d['t']: my_dict.pop(d['t'],0) + d['Y'] + d['X']})
... 
>>> my_dict
{1: 55, 2: 800, 3: 0.8, 4: 5500}
>>> my_list=[]
>>> for k in sorted(my_dict.keys()):
...     my_list.append({"t":k,"SUM":my_dict[k]})
... 
>>> my_list
[{'SUM': 55, 't': 1}, {'SUM': 800, 't': 2}, {'SUM': 0.8, 't': 3}, {'SUM': 5500, 't': 4}]
>>> 

答案 1 :(得分:0)

你可以这样做。

A=[{'t':1, 'X':10, 'Y': 15},
   {'t':4, 'X':2500, 'Y': 3000},
   {'t':1, 'X':20, 'Y': 10},
   {'t':3, 'X':0.10, 'Y': 0.40},
   {'t':2, 'X':400, 'Y': 400},
   {'t':3, 'X':0.20, 'Y': 0.10},
]

output_dict = {}
for item in A:
    if item['t'] in output_dict:
        output_dict[item['t']] +=  item['X'] + item['Y']
    else:
        output_dict[item['t']] =  item['X'] + item['Y']

output_list = []
for key in sorted(output_dict.keys()):
    output_list.append({"t":key, "SUM":output_dict[key]})

for item in output_list:
    print(item)

输出:

{'t': 1, 'SUM': 55}
{'t': 2, 'SUM': 800}
{'t': 3, 'SUM': 0.8}
{'t': 4, 'SUM': 5500}
相关问题