Python-TypeError:"int"对象不可迭代 [英] Python - TypeError: 'int' object is not iterable

查看:370
本文介绍了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].然后,我想将这些数字加在一起(我还没有开始,但是我对如何做有一些想法).

I am looking to make a loop so that for each element in the list, it will get broken down into each of it's characters. For example, say the number 137 was in the list then it would be turned into [1,3,7]. Then I want to add these numbers together (I haven't started that bit yet but I have some idea of how to do it).

但是,我不断收到错误消息

However, I keep getting the error message

TypeError: 'int' object is not iterable

当我尝试运行此程序时.

when I try and run this.

我在做什么错了?

推荐答案

您的问题在于以下行:

number4 = list(cow[n])

它尝试采用cow[n],它返回一个整数,并使其成为列表.如下所示,这是行不通的:

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

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

也许您打算将cow[n] 放在列表中:

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

请参见下面的演示

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


我还想解决两件事:


Also, I wanted to address two things:

  1. 您的while陈述结尾缺少:.
  2. 像这样使用input被认为是非常危险的,因为它将其输入评估为真实的Python代码.最好使用 raw_input ,然后使用 int .
  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.


要拆分数字,然后根据需要添加它们,我首先将数字设置为字符串.然后,由于字符串是可迭代的,因此可以使用 sum :


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

这篇关于Python-TypeError:"int"对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆