如何创建一个整数列表,该整数列表是字典中一组列表中所有整数的总和? [英] How to make a list of integers that is the sum of all the integers from a set of lists in a dict?

查看:57
本文介绍了如何创建一个整数列表,该整数列表是字典中一组列表中所有整数的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个由n个键组成的字典.每个键都映射到长度一致的整数列表.我现在想做的是一个新列表,它表示字典列表中每个点的整数之和.为了说明:

Let's assume I have a created a dict that is made up of n keys. Each key is mapped to a list of integers of a consistent length. What I want to make now is a new list that represents the sum of the integers at each point in lists of the dict. To illustrate:

my_dict = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}

total_sum_list = []

for key in my_dict.keys():
    total_sum_list += ###some way of adding the numbers together

预期输出:

total_sum_list = [6,9,12,15]

如上所述,我不确定如何设置此for循环,以便可以创建类似total_sum_list的列表.我曾经尝试过对列表进行理解,但是到目前为止,我的努力还没有成功.有什么建议吗?

As demonstrated above, I am not sure how to set up this for loop so that I can create a list like total_sum_list. I have tried putting together a list comprehension, but my efforts have not been successful thus far. Any suggestions?

推荐答案

您需要的是对列表进行转置,以便可以对列求和.因此,在字典值(键可以忽略)上使用zip,在列表理解中使用sum:

What you need is to transpose the lists so you can sum the columns. So use zip on the dictionary values (keys can be ignored) and sum in list comprehension:

一行:

total_sum_list = [sum(x) for x in zip(*my_dict.values())]

结果:

[6, 9, 12, 15]

工作原理:

zip交织值.我正在使用参数解包来传递dict值是zip的参数(如zip(a,b,c)).因此,当您这样做时:

zip interleaves the values. I'm using argument unpacking to pass the dict values are arguments to zip (like zip(a,b,c)). So when you do:

for x in zip(*my_dict.values()):
    print(x)

您得到(如tuple):

(1, 3, 2)
(2, 4, 3)
(3, 5, 4)
(4, 6, 5)

数据随时可以求和(即使顺序不同,但我们不在乎,因为加法是可交换的:))

data are ready to be summed (even in different order, but we don't care since addition is commutative :))

这篇关于如何创建一个整数列表,该整数列表是字典中一组列表中所有整数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆