繁体   English   中英

如何修复'int object 不可迭代'

[英]How to fix 'int object is not iterable'

我正在尝试将所有整数添加到“a”变量中,但是这个“a”变量既不是列表也不是字符串,尽管其中有各种不同的整数。

我正在编写一个 Python 程序,该程序给出用户提供的正 integer num,打印其所有除数的总和。 我已经尝试将这个“a”变量设为列表,但发生了同样的错误

import math
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a) 
for i in (b):
    x = num / i
    if math.floor(x) == x:
            c = list(i)

我已经尝试将这个“a”变量设为列表,但发生了同样的错误:“int object is not iterable”

list()创建一个新列表,其参数必须是可迭代的(例如,元组、另一个列表等)。 如果你只传递一个数字i ,它就行不通。

我想你想要做的不是每次循环迭代都创建一个新列表,而是将i元素添加到已经存在的列表中。
您可以通过以下方式实现:

num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
divisors = []  # create a new list where the results will be stored
for i in (b):
    x = num / i
    if math.floor(x) == x:
        divisors.append(i)  # add the number at the end of the list

如果要对所有除数求和,请使用:

sum(divisors)

实现相同结果的更“Pythonic”(诚然,如果您不习惯列出理解,不一定更容易阅读)方法是:

num = int(input("Num: "))
divisors_sum = sum(i for i in range(1, num + 1) if num//i == num/i)

我假设你在这里使用 Python 3 。 在 Python 3, //是地板除法,所以你不必使用math.floor 有关// vs. /的更多详细信息,请参阅这篇文章

您可以在循环之外创建一个空列表: c = [] ,然后每次 append 通过c.append(i)应用程序将一个元素添加到列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM