[英]How can i sum up all values with the same index in a dictionary which each key has a nested list as a value?
I have a dictionary, each key of dictionary has a list of list (nested list) as its value.我有一本字典,字典的每个键都有一个列表列表(嵌套列表)作为其值。 What I want is imagine we have:我想要的是想象我们有:
x = {1: [[1, 2], [3, 5]], 2: [[2, 1], [2, 6]], 3: [[1, 5], [5, 4]]}
My question is how can I access each element of the dictionary and concatenate those with same index: for example first list from all keys:我的问题是如何访问字典的每个元素并连接具有相同索引的元素:例如所有键的第一个列表:
[1,2] from first keye +
[2,1] from second and
[1,5] from third one
How can I do this?我怎样才能做到这一点?
You can access your nested list easily when you're iterating through your dictionary and append it to a new list and the you apply the sum
function.当您遍历字典并将 append 迭代到新列表并应用sum
function 时,您可以轻松访问嵌套列表。
Code:代码:
x={1: [[1,2],[3,5]] , 2:[[2,1],[2,6]], 3:[[1,5],[5,4]]}
ans=[]
for key in x:
ans += x[key][0]
print(sum(ans))
Output: Output:
12
Assuming you want a list of the first elements, you can do:假设您想要第一个元素的列表,您可以执行以下操作:
>>> x={1: [[1,2],[3,5]] , 2:[[2,1],[2,6]], 3:[[1,5],[5,4]]}
>>> y = [a[0] for a in x.values()]
>>> y
[[1, 2], [2, 1], [1, 5]]
If you want the second element, you can use a[1]
, etc.如果你想要第二个元素,你可以使用a[1]
等。
The output you expect is not entirely clear (do you want to sum? concatenate?), but what seems clear is that you want to handle the values as matrices.您期望的 output 并不完全清楚(您想求和吗?连接?),但似乎很清楚的是您想将值作为矩阵处理。
You can use numpy
for that:您可以为此使用numpy
:
import numpy as np
sum(map(np.array, x.values())).tolist()
output: output:
[[4, 8], [10, 15]] # [[1+2+1, 2+1+5], [3+2+5, 5+6+4]]
import numpy as np
np.hstack(list(map(np.array, x.values()))).tolist()
output: output:
[[1, 2, 2, 1, 1, 5], [3, 5, 2, 6, 5, 4]]
As explained in How to iterate through two lists in parallel?如如何并行遍历两个列表中所述? , zip
does exactly that: iterates over a few iterables at the same time and generates tuples of matching-index items from all iterables. , zip
正是这样做的:同时迭代几个迭代并从所有迭代生成匹配索引项的元组。
In your case, the iterables are the values
of the dict.在您的情况下,迭代是字典的values
。 So just unpack the values to zip
:所以只需将值解压缩到zip
:
x = {1: [[1, 2], [3, 5]], 2: [[2, 1], [2, 6]], 3: [[1, 5], [5, 4]]}
for y in zip(*x.values()):
print(y)
Gives:给出:
([1, 2], [2, 1], [1, 5])
([3, 5], [2, 6], [5, 4])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.