int对象不是可迭代的python(int object is not iterable python)

编程入门 行业动态 更新时间:2024-10-25 22:35:52
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]) 3

Why 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]) 5

As 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

更多推荐

本文发布于:2023-08-01 21:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365039.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   迭代   int   iterable   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!