[英]How to add elements from a dictonary of lists in python
given a dictionary of lists 给出一个列表字典
vd = {'A': [1,0,1], 'B':[-1,0,1], 'C':[0,1,1]}
I want to add the lists element wise. 我想明智地添加列表元素。 So I want to add first element from list A to first element of list B vice versa the complexity is that you cannot rely on the labels being A, B, C. It can be anything.
所以我想将列表A中的第一个元素添加到列表B的第一个元素,反之亦然,复杂性是你不能依赖标签A,B,C。它可以是任何东西。 second the length of the dictionary is also variable.
第二,字典的长度也是可变的。 here it is 3. but it could be 30.
这里是3.但它可能是30。
The result i need is a list [0, 1, 3] 我需要的结果是列表[0,1,3]
所以你只想按元素加起所有值?
[sum(l) for l in zip(*vd.values())]
In short: 简而言之:
>>> map(sum, zip(*vd.values()))
[0, 1, 3]
Given a dictionary: 鉴于字典:
>>> vd = {'A': [1,0,1], 'B': [-1,0,1], 'C': [0,1,1]}
We can get the values : 我们可以获得价值 :
>>> values = vd.values()
>>> values
[[1, 0, 1], [-1, 0, 1], [0, 1, 1]]
>>> zipped = zip(*values)
>>> zipped
[(1, -1, 0), (0, 0, 1), (1, 1, 1)]
Note that zip
zips up each argument; 请注意,
zip
每个参数; it doesn't take a list of things to zip up. 它没有列出要拉链的东西。 Therefore, we need the
*
to unpack the list into arguments. 因此,我们需要
*
将列表解压缩为参数。
If we had just one list, we could sum them: 如果我们只有一个列表,我们可以将它们相加 :
>>> sum([1, 2, 3])
6
However, we have multiple, so we can map over it: 但是,我们有多个,所以我们可以映射它:
>>> map(sum, zipped)
[0, 1, 3]
All together: 全部一起:
>>> map(sum, zip(*vd.values()))
[0, 1, 3]
This approach is also easily extensible; 这种方法也很容易扩展; for example, we could quite easily make it average the elements rather than sum them.
例如,我们可以很容易地将它们作为平均值而不是求和。 To do that, we'd first make an
average
function: 要做到这一点,我们首先要做一个
average
功能:
def average(numbers):
# We have to do the float(...) so it doesn't do an integer division.
# In Python 3, it is not necessary.
return sum(numbers) / float(len(numbers))
Then just replace sum
with average
: 然后用
average
替换sum
:
>>> map(average, zip(*vd.values()))
[0.0, 0.3333, 1.0]
vd = {'A': [1,0,1], 'B':[-1,0,1], 'C':[0,1,1]}
vd_keys = list(vd.keys())
rt = vd[vd_keys.pop()].copy() # copy otherwise rt and vd[vd_keys.pop()] will get synced
for k in vd_keys:
for i in range(len(rt)):
rt[i] += vd[k][i]
print(rt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.