对来自不同列表的相同索引的元素求和 [英] Sum elements of same index from different lists

查看:42
本文介绍了对来自不同列表的相同索引的元素求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,其中每个内部列表代表电子表格中的一行.使用我当前的数据结构,如何对具有相同索引的内部列表中的每个元素执行操作(这基本上相当于在电子表格中的一列下执行操作.)

这是我正在寻找的示例(在加法方面)

<预><代码>>>>lisolis = [[1,2,3], [4,5,6], [7,8,9]]>>>sumindex = [1+4+7, 2+5+8, 3+6+9]>>>sumindex = [12, 15, 18]

这个问题可能可以通过切片来解决,但我无法清楚地看到如何做到这一点.有没有一个漂亮的工具/库可以为我完成这个任务?

解决方案

只需使用 zip:

sumindex = [sum(elts) for elts in zip(*lisolis)]

I have a list of lists, where each inner list represents a row in a spreadsheet. With my current data structure, how can I perform an operation on each element on an inner list with the same index ( which amounts to basically performing operations down a column in a spreadsheet.)

Here is an example of what I am looking for (in terms of addition)

>>> lisolis = [[1,2,3], [4,5,6], [7,8,9]]

>>> sumindex = [1+4+7, 2+5+8, 3+6+9]

>>> sumindex = [12, 15, 18]

This problem can probably be solved with slicing, but I'm unable to see how to do that cleanly. Is there a nifty tool/library out there that can accomplish this for me?

解决方案

Just use zip:

sumindex = [sum(elts) for elts in zip(*lisolis)]

这篇关于对来自不同列表的相同索引的元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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