development

Python-TypeError : 'int'개체는 반복 할 수 없습니다.

big-blog 2021. 1. 7. 20:37
반응형

Python-TypeError : 'int'개체는 반복 할 수 없습니다.


내 코드는 다음과 같습니다.

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. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use 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
>>>

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

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

ReferenceURL : https://stackoverflow.com/questions/19523563/python-typeerror-int-object-is-not-iterable

반응형