这是我的代码:

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

它try 取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] inside列在一张 list 上:

number4 = [cow[n]]

请参见下面的演示:

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

此外,我想解决两件事:

  1. 你的while语句末尾缺少:.
  2. 这样使用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
>>>

Python-3.x相关问答推荐

如何在Django中创建两个不同权限的用户?

如何使用regex将电话号码和姓名从文本字符串中分离出来

像计数不显示在html和想知道如果我的模型设置正确

基于另一个数据帧计算总和

如何定义部署用 Python 编写的 Firestore 第二代函数的区域/位置?

Django 模型类方法使用错误的 `self`

在 python pandas 中设置条件和分配新值

有没有办法使用 python opencv 计算与图像的白色距离

使用 pandas 数据帧映射到中转( node )点的跨容量请求

Python defaultdict 在获取时返回 None,尽管使用默认值初始化

从 yahoo Finance python 一次下载多只股票

Python:pprint的模块错误,打印没有错误

获取嵌套字典的所有键

是否有与 Laravel 4 等效的 python?

使用逗号时,除了处理程序中的语法无效

使用打印时,用+连接是否比用,分隔更有效?

IronPython 3 支持?

Python heapify() 时间复杂度

用 numpy nan 查找列表的最大值

matplotlib - 模块sip没有属性setapi