Python-TypeError:“int”对象不是iterab

2024-04-24 18:46:10 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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

当我试着运行这个。

我做错什么了?


Tags: to代码importyou列表inputrange数字
2条回答

你的问题是这条线:

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. while语句末尾缺少:
  2. 像那样使用input被认为是非常危险的,因为它将其输入计算为真正的Python代码。最好在这里使用^{},然后将输入转换为带^{}的整数。

若要拆分数字,然后按您所需添加它们,我将首先将数字设为字符串。然后,由于字符串是可iterable的,您可以使用^{}

>>> 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
>>>

这很简单,你正在试图转换一个整数到一个列表对象!!!当然它会失败,它应该。。。

要通过使用您提供的示例向您演示/证明这一点…只需对下面的每个案例使用type函数,结果就可以说明问题了!

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

相关问题 更多 >