sum(1 for _ in lista) 到底是怎么在进行运算?

比如 lista 是一个含3个数的数组,或者迭代器。
那么
sum(1 for _ in lista) 返回就是3,
sum(2 for _ in lista) 返回就是6
但是这其中的逻辑是啥??
sum不是第一个参数必须是迭代器吗?

Jason990420
最佳答案
>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

Python 词汇表

以下内容说明 (1 for i in lista) 是一个产生器, 也是一个可迭代的对象.

>>> lista = [1, 2, 3]
>>> g = (1 for i in lista)
>>> g
<generator object <genexpr> at 0x0000020B30413FC0>
>>> from collections.abc import Iterable
>>> isinstance(g, Iterable)
True
>>> next(g)
1
>>> next(g)
1
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> g.__iter__
<method-wrapper '__iter__' of generator object at 0x0000020B30413FC0>
>>> iter(g)
<generator object <genexpr> at 0x0000020B30413FC0>
3年前 评论
讨论数量: 3
Jason990420
>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

Python 词汇表

以下内容说明 (1 for i in lista) 是一个产生器, 也是一个可迭代的对象.

>>> lista = [1, 2, 3]
>>> g = (1 for i in lista)
>>> g
<generator object <genexpr> at 0x0000020B30413FC0>
>>> from collections.abc import Iterable
>>> isinstance(g, Iterable)
True
>>> next(g)
1
>>> next(g)
1
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> g.__iter__
<method-wrapper '__iter__' of generator object at 0x0000020B30413FC0>
>>> iter(g)
<generator object <genexpr> at 0x0000020B30413FC0>
3年前 评论

首先看sum这个函数的定义:

Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

参数一是一个iterable对象,参数之间以comma(即,)分开。总共就俩参数=>[iterable,start]。

回归你的问题,sum (1 for _ in lista)首先这不符合多个参数的情况,其次这是一种推导式的写法,比如列表推导式[x for x in iterable object]生成器推导式(x for x in iterable object),二者区别只是[]()不一样。

所以你的写法就构成了一种推导式,所以就是一个可迭代对象,sum是可以自动计算的。

3年前 评论

@Jason990420 @runstone 谢谢。 一直以为推导式只能是使用字母或者_。没有想到还有第一个字母1,2,。。的写法

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!