int对象不是可迭代的python(int object is not iterable python)
python
我正在尝试学习python reduce函数。
这是一些对我没有意义的代码
>>> x = [1,2,3] >>> reduce(sum, [b for b in x if b > 0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> reduce(sum, [b for b in x if b > 2]) 3当b> 2但b> 0时,为什么它可以工作?
代码看起来几乎完全相同
I am trying to learn python reduce function.
This is some code that does not make sense to me
>>> x = [1,2,3] >>> reduce(sum, [b for b in x if b > 0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> reduce(sum, [b for b in x if b > 2]) 3Why does it work when b > 2 but not b > 0
The code seems almost exactly the same
最满意答案
正如摩西所指出的那样“总和在第一次迭代中消耗了迭代”,所以让我们一起玩吧
>>> sum(1,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> sum([1,2]) 3 >>> sum(x) 6 >>> sum([b for b in x if b >0]) 6 >>> reduce(lambda x, y: x+y, x) 6 >>> reduce(lambda x, y: x+y, [b for b in x if b > 0]) 6 >>> reduce(lambda x, y: x+y, [b for b in x if b > 1]) 5As Moses points out "sum consumes the iterable in the first iteration" so let's play with it
>>> sum(1,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> sum([1,2]) 3 >>> sum(x) 6 >>> sum([b for b in x if b >0]) 6 >>> reduce(lambda x, y: x+y, x) 6 >>> reduce(lambda x, y: x+y, [b for b in x if b > 0]) 6 >>> reduce(lambda x, y: x+y, [b for b in x if b > 1]) 5更多推荐
发布评论