嵌套列表中第一个值的总和

2022-11-05Python开发问题
5

本文介绍了嵌套列表中第一个值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在传统的python中,sum函数给出一个list的总和:

In traditional python, the sum function gives the sum of a list:

sum([0,1,2,3,4])=10

另一方面,如果你有一个嵌套列表怎么办:

On the other hand, what if you have a nested list as so:

sum([[1,2,3],[4,5,6],[7,8,9]])

我们发现错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

除此之外,我们如何在嵌套列表中找到第一个值(索引 0)的 sum?如:

In addition to this, how could we find the sum of the first values (index 0) in a nested list? Such as:

something([[1,2,3],[4,5,6],[7,8,9]])=12

推荐答案

要获得所有第一个元素的总和,您需要有一个生成器表达式

To get the sum of all the first elements you need to have a generator expression

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> sum(i[0] for i in a)
12

您得到 unsupported operand type(s) for +: 'int' and 'list' 因为您尝试添加三个列表,这不是所需的行为.

You are getting unsupported operand type(s) for +: 'int' and 'list' because you are trying to add the three lists which is not the desired behavior.

如果您想要一个第一个元素的列表,然后找到它们的总和,您可以尝试使用列表推导

If you want a list of first elements and then find their sum, you can try a list comprehension instead

>>> l = [i[0] for i in a]
>>> l
[1, 4, 7]
>>> sum(l)
12

或者您可以调用 __next__ 方法,因为列表是可迭代的(如果 Py3)

Or you can call the __next__ method as list is an iterable (If Py3)

>>> sum(zip(*a).__next__())
12

这篇关于嵌套列表中第一个值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11