Python -TypeError : 'int' object is not iterable

标签 python python-3.x list loops iterable

这是我的代码:

import math

print("Hey, lets solve Task 4 :)")

number1 = input("How many digits do you want to look at? ")
number2 = input("What would you like the digits to add up to? ")

if number1 == 1:
    cow = range(0,10)
elif number1 == 2:
    cow = range(10,100)
elif number1 == 3:
    cow = range(100,1000)
elif number1 == 4:
    cow = range(1000,10000)
elif number1 == 5:
    cow = range(10000,100000)
elif number1 == 6:
    cow = range(100000,1000000)
elif number1 == 7:
    cow = range(1000000,10000000)
elif number1 == 8:
    cow = range(10000000,100000000)
elif number1 == 9:
    cow = range(100000000,1000000000)
elif number1 == 10:
    cow = range(1000000000,10000000000)

number3 = cow[-1] + 1

n = 0
while n < number3:
    number4 = list(cow[n])
    n += 1

我希望制作一个循环,以便对于列表中的每个元素,它将被分解为每个字符。例如,假设数字 137 在列表中,然后将其变成 [1,3,7] 。然后,我想将这些数字添加在一起(我还没有开始这一点,但是我对如何做)。

但是,我一直收到此错误消息:

TypeError: 'int' object is not iterable

我做错了什么?

最佳答案

您的问题与此行:

number4 = list(cow[n])

它试图取 cow [n] ,它返回整数,并将其作为列表。如下所示,这无效:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

也许您打算将 cow [n] 内部

number4 = [cow[n]]

请参阅下面的演示:

>>> a = 1
>>> [a]
[1]
>>>

另外,我想解决两件事:

  1. 您的句子缺少:最后。
  2. 使用输入之类的人认为非常危险,因为它将其输入评估为真实的Python代码。在这里最好使用raw_input,然后将输入转换为使用int的整数。

要拆分数字,然后像您想要的那样添加它们,我首先将数字作为字符串。然后,由于字符串是可以的,因此您可以使用sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

关于Python -TypeError : 'int' object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523563/

相关文章:

python - 迭代两个嵌套的二维列表,其中 list2 具有 list1 的行号

python - 索博尔随机号生成器 python

linux - 我无法使用导入命令

python - 使用 csv.DictWriter 输出内存中的 gzip 压缩 csv 文件?

python - 连接不同列表中的两个字符串

javascript - 从列表项中删除类并使用 jquery 将类添加到不同的列表项

c# - 列表集索引c#

python - Django Rest Framework 在后台从模型中导出 csv 数据

python - 将图标添加到选项卡(QTabWidget)?

python-3.x - 在Windows 10上的Docker Toolbox上运行Splash