我有一个列表字典,如下:
defaultdict (& lt;类列表的祝辞,{0:[(1.0,2.0,3.0),(7.0,8.0,9.0)],1:[(4.0,5.0,6.0),(10.0,11.0,12.0)]})
我需要一个字典,它通过求和列表的值来减少维度,例如下面
{0: [6.0, 24.0], 1: [15.0, 33.0]}
提示:6.0 = [1.0+2.0 +3.0]24.0 = (7.0 + 8.0 + 9.0)
遍历键并在列表推导式中对每个子列表求和:
d = {0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]}
for k in d:
d[k] = [sum(l) for l in d[k]]
>>> d
{0: [6.0, 24.0], 1: [15.0, 33.0]}
也适用于defaultdict
。
通过使用字典推导式,无需修改原字典即可获得新字典:
new_d = {k:[sum(l) for l in d[k]] for k in d}
递归是对嵌套字典进行横向和求值的有效方法
defaultDict={0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]}
def walk_the_tree(inputDict,parent_index=None):
if isinstance(inputDict,dict):
for key, value in inputDict.items():
if isinstance(value,list):
ret_index,type,result=walk_the_tree(value,key)
print(key, ret_index, type, result)
elif isinstance(inputDict,list):
sum=0
for index,alist in enumerate(inputDict):
#print(index,alist)
ret_index,type,value=walk_the_tree(alist,index)
if type=="Sum List":
print ("replace value",parent_index, index, value)
defaultDict[parent_index][index]=value
print(type,value)
if type=="Leaf":
sum+=value
return index,"Sum List",sum
else:
return 0,"Leaf", inputDict
return
walk_the_tree(defaultDict)
print(defaultDict)
output:
{0: [6.0, 24.0], 1: [15.0, 33.0]}