这是我的代码:
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
当我尝试运行它时。
我做错了什么?
答案 0 :(得分:81)
你的问题在于这一行:
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]
>>>
另外,我想解决两件事:
:
。input
被认为是非常危险的,因为它将其输入评估为真正的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
>>>
答案 1 :(得分:2)
如果情况是:
n=int(input())
代替 -> for i in n: -> 给出错误 - 'int' 对象不可迭代
使用 -> for i in range(0,n): -> 工作正常..!
答案 2 :(得分:0)
这很简单,您正在尝试将整数转换为列表对象!当然它将失败,并且应该...
通过使用您提供的示例向您证明/证明这一点...只需对每种情况使用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
>>>
答案 3 :(得分:0)
def hourglassSum(arr):
sum1 = []
# Write your code here
for i in range(0,len(arr)-2):
for j in range(0,len(arr)-2):
x = sum(arr[i][j]+arr[i+1][j+1]+arr[i+2][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+1]+arr[i+2][j+2])
sum1.append(x)
#sum1.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
return max(sum1)
# Why x = sum(arr[i][j]+arr[i+1][j+1]+arr[i+2][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+1]+arr[i+2][j+2]) is showing TypeError: 'int' object is not iterable
如果我们在语句下面运行注释语句,它会正常运行..