简体   繁体   English

作为列表列表的字典元素的总和

[英]Summation of elements of dictionary that are list of lists

d = {
  'a': [[1, 2, 3], [1, 2, 3]],
  'b': [[2, 4, 1], [1, 6, 1]],
}

def add_element(lst):
    ad = [sum(i) for i in zip(*lst)]
    return ad

def csv_reducer2(dicty):
    return {k: list(map(add_element, v)) for k, v in dicty.items()}

csv_reducer2(d)

required output: 所需产量:

{'b': [3, 10, 2], 'a': [2, 4, 6]}

Above is the code I have been trying but it gives an error 上面是我一直在尝试的代码,但它给出了一个错误

zip argument #1 must support iteration zip参数#1必须支持迭代

>>> d = {'a': [[1, 2, 3], [1, 2, 3]], 'b': [[2, 4, 1], [1, 6, 1]]}
>>> {k: map(sum, zip(*v)) for k, v in d.items()}
{'a': [2, 4, 6], 'b': [3, 10, 2]}

The following will work on Python 2 or 3: 以下内容适用于Python 2或3:

>>> {k: [a + b for a, b in zip(*v)] for k, v in d.items()}
{'a': [2, 4, 6], 'b': [3, 10, 2]}

The issue with your code is you are mapping add_element to every individual element in v inside your dictionary comprehension. 您的代码的问题是您将add_element映射到字典理解中的v每个单独元素。 This passes a one-dimensional list to zip in add_element , resulting in your error (since individual integers don't support iteration. 这会将一维列表传递给add_element zip ,从而导致错误(因为单个整数不支持迭代。

To fix your original code, the only change you need to make is: 要修复原始代码,您需要做的唯一更改是:

return {k: list(map(add_element, v)) for k, v in dicty.items()}

-> - >

return {k: add_element(v) for k, v in dicty.items()}

Because zip(*lst) is trying to transpose multiple rows into columns, but you are only passing it single rows through your original map 因为zip(*lst)试图将多行转换为列,但是您只在原始map传递单行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM