将defaultdict(列表)的总和映射到一个列表

时间:2016-09-22 17:26:12

标签: python list python-3.x mapping defaultdict

我有大量数据格式,有点像d.items()的{​​{1}}。见下文:

defaultdict(list)

我想将嵌套列表中每个数据值的总和映射到相同位置或索引中的相应对应项,以产生如下的最终总和:

products = [(('blue'), ([2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4], [2, 4, 2, 4, 2, 4, 2, 4, 2, 4])),
        (('yellow'), ([1, 3, 1, 3, 1, 3, 1, 3, 1, 3], [1, 3, 1, 3, 1, 3, 1, 3, 1, 3], [1, 3, 1, 3, 1, 3, 1, 3, 1, 3])),
        (('red'), ([1, 1, 1, 1, 1, 2, 5, 4, 6, 4], [2, 5, 3, 4, 8, 1, 1, 1, 1, 1], [8, 6, 3, 9, 2, 1, 1, 1, 1, 1]))]

使用循环,可以轻松完成,如下所示:

['blue', 6, 12, 6, 12, 6, 12, 6, 12, '6.000000', 12]
['yellow', 3, 9, 3, 9, 3, 9, 3, 9, '3.000000', 9]
['red', 11, 12, 7, 14, 11, 4, 7, 6, '8.000000', 6]

当产品的尺寸为数百万时,即产生非常耗时的问题。所以我想实现将每个值映射到嵌套列表中相应键的相应值。这就是我试过的:

def summation(products):

    sums = []

    for item in products:
            sums.append([(item[0]),
                     sum(int(x[0]) for x in item[1]),
                     sum(int(x[1]) for x in item[1]),
                     sum(int(x[2]) for x in item[1]),
                     sum(int(x[3]) for x in item[1]),
                     sum(int(x[4]) for x in item[1]),
                     sum(int(x[5]) for x in item[1]),
                     sum(int(x[6]) for x in item[1]),
                     sum(int(x[7]) for x in item[1]),
                     "{:.6f}".format(sum(float(x[8]) for x in item[1])),
                     sum(int(x[9]) for x in item[1])])

    for s in sums:
        print(s)

但是,我收到以下错误:

def mappingSum(products):
    sums = []

    for item in products:
        sums.append([item[0], map((sum(x), sum(y), sum(z)) for x, y, z in item[1])])



    for s in sums:
        print(s)

我不知道如何解决它,我不确定TypeError: map() must have at least two arguments. 是否是完成任务的正确工具。

2 个答案:

答案 0 :(得分:3)

根据我的理解,您需要压缩列表中的子列表并总结它们:

>>> sums = [(key, [sum(value) for value in zip(*values)]) for key, values in products]
>>> for s in sums:
...     print(s)
... 
('blue', [6, 12, 6, 12, 6, 12, 6, 12, 6, 12])
('yellow', [3, 9, 3, 9, 3, 9, 3, 9, 3, 9])
('red', [11, 12, 7, 14, 11, 4, 7, 6, 8, 6])

答案 1 :(得分:2)

作为@ alecxe的答案的替代方案,请考虑以下使用map和一个很好的列表literal-unpack:

res = [(k, [*map(sum, zip(*v))]) for k, v in products]

这会产生:

[('blue', [6, 12, 6, 12, 6, 12, 6, 12, 6, 12]),
 ('yellow', [3, 9, 3, 9, 3, 9, 3, 9, 3, 9]),
 ('red', [11, 12, 7, 14, 11, 4, 7, 6, 8, 6])]

这稍微快一些,但由于文字解包而需要Python >= 3.5。如果在早期版本中,您必须将其包装在list调用中以解压缩map迭代器:

res = [(k, list(map(sum, zip(*v)))) for k, v in products]