【问题标题】:How can I correct an "'int' object is not iterable" error using Python?如何使用 Python 纠正“'int' object is not iterable”错误?
【发布时间】:2019-07-22 20:43:56
【问题描述】:
def square_each(nums):
    import math
    for i in range(len(nums)):
        nums[i] = nums[i]**2

def sum_list(nums):
    for values in nums:
        sums = sum(values)
        print(sums)

def to_numbers(str_list):
    numbers = [int(strings) for strings in str_list]
    return numbers

def main():
    print("This program computes the sum of the squares of numbers read from a file.")
    filename = input("Please enter the file name:")
    file = open(filename, 'r')
    line = file.readline()
    list1 = line.split(" ")
    numbers = to_numbers(list1)
    square_each(numbers)
    sums = sum_list(numbers)
    print("The sum of the squares of the numbers in the file is{0}".format(sums))

    main()



Traceback (most recent call last):

File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 35, in <module>

 File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 32, in main
sums = sum_list(numbers)

 File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 16, in sum_list
sums = sum(values)

TypeError: 'int' object is not iterable

我打开了一个包含字符串(数字)列表的文件。然后我使用三个函数将字符串转换为数字,对每个数字求平方,并对数字列表求和。最后一个函数 main() 包含这三个函数。但我有一个“int”对象不可迭代错误。如何在此处更正此错误?

【问题讨论】:

  • 在 sum_list 函数中,删除 for 循环并返回 sum(nums)

标签: python string int typeerror


【解决方案1】:

要详细说明上面的评论,您不需要通过 for 循环运行您的列表,因为 sum 函数会为您处理。实际上,您的 sum_list 函数非常多余。 工作函数如下:

def sum_list(nums):
    sums = sum(nums)
    return sums

我会删除该功能,然后做:

def square_each(nums):
    import math
    for i in range(len(nums)):
        nums[i] = nums[i]**2

def to_numbers(str_list):
    numbers = [int(strings) for strings in str_list]
    return numbers

def main():
    print("This program computes the sum of the squares of numbers read from a file.")
    filename = input("Please enter the file name:")
    file = open(filename, 'r')
    line = file.readline()
    list1 = line.split(" ")
    numbers = to_numbers(list1)
    square_each(numbers)
    sums = sum(numbers) # <- this instead of your function presuming that you are feeding a list
    print("The sum of the squares of the numbers in the file is{0}".format(sums))

main()

python中sum函数的一些阅读:
http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsCalculatingtheSumofaListofNumbers.html

我选择这个例子的原因是因为它显示了我认为你的函数试图实现的目标——如果你的输入还不是一个列表;但在你的情况下,它并不是真正需要的。

【讨论】:

    猜你喜欢
    • 2022-12-15
    • 1970-01-01
    • 2020-11-07
    • 2018-06-29
    • 2022-11-14
    • 2017-10-14
    • 2019-04-12
    • 2016-02-18
    • 2022-11-02
    相关资源
    最近更新 更多