如何对 N 个列表的元素求和?
- 作者: 周心痴727
- 来源: 51数据库
- 2022-10-21
问题描述
谁能给我一个提示如何聚合(总结)多个列表的特定元素?
can anybody please give me a hint how to aggregate (sum up) specific elements of multiple lists?
例如,我有 20 个名称模式相似的列表,每个列表代表相应家庭(代理)随时间推移的消费支出(即索引):
For example I have 20 lists with a similar name pattern, each representing consumption spending over time (i.e. index) of the corresponding household (agent):
c_agent_0 = [10.0, 11.0, ...] . . . c_agent_19 = [8.0, 9.0, ...]
我需要类似 value = sum of index what's in c_agent_*[whatever]
I need something like value = sum of index whatever's in c_agent_*[whatever]
推荐答案
使用 zip 将列表组合"成一个,然后对每个索引的元素求和:
Use zip to "combine" lists into single one, then sum elements for each index:
c_agent_0 = [10.0, 11.0, 12.0, 13.0, 14.0] c_agent_1 = [1.1, 12.3, 14.2, 13.2, 14.3] c_agent_2 = [1.4, 12.1, 14.5, 13.1, 14.2] zipped_list = zip(c_agent_0, c_agent_1, c_agent_2) print zipped_list print [sum(item) for item in zipped_list]
打印
[(10.0, 1.1, 1.4), (11.0, 12.3, 12.1), (12.0, 14.2, 14.5), (13.0, 13.2, 13.1), (14.0, 14.3, 14.2)] [12.5, 35.4, 40.7, 39.3, 42.5]
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0