Python typeerror int对象不可迭代,sum函数问题(我认为)

时间:2016-11-21 00:39:21

标签: python typeerror

该计划的目的是询问用户他们在3天(周末)衣服开车的每一天收集了多少衣物,平均,在第二个周末再做一次,然后平均两个周末(每天的衣服)。

这是我的代码:

import math

num_clothes = int() 
weekend_total = int() 
weekend_avg = float() 
total_clothes = int() 
total_avg = float() 
index = int()


index = 1 
while index <= 2: 
    index = 1 
    while index <= 3: 
        num_clothes = int(input("How many articles of clothing did you collect today? ")) 
        index = index + 1

    weekend_total = sum(num_clothes) 
    weekend_avg = weekend_total / 3 
    print("Total Collected:\t", weekend_total) 
    print("Weekend Average:\t", weekend_avg) 
    index = index + 1`1

total_clothes = sum(weekend_total) 
total_avg = total_clothes / 6 
print("Total Number of Clothing Collected:\t", total_clothes) 
print("Average Collected:\t", total_avg)

这是我不断得到的错误:

Traceback (most recent call last):
  File "G:\ITCS 1140\labs\python\lab 9.py", line 17, in <module>
    weekend_total = sum(num_clothes)
TypeError: 'int' object is not iterable

我想把num_clothes变成一个列表并用sum(num_clothes)添加它的所有值。

2 个答案:

答案 0 :(得分:0)

您的num_clothes是 int 类型的变量,您将此变量作为参数传递给sum function

weekend_total = sum(num_clothes)

您可以通过文档看到,如果要正确求和,则需要将迭代器作为参数传递。

如果您想要阅读用户的列表,请尝试将输入更改为:

    a = [int(x) for x in input().split()]  

Example
-------

    >>> a = [int(x) for x in input().split()]
    3 4 5
    >>> a
    [3, 4, 5]
    >>> sum(a)
    12
    >>>

Source

或者,您可以保留代码,并将num_clothes更改为list()。然后,在读取输入后,将结果附加到列表中:

num_clothes = list()

...

num_clothes.append(int(input(...))

...

weekend_total = sum(num_clothes)

答案 1 :(得分:0)

sum()是一个添加可迭代对象(如列表

)的所有对象的函数
list = [1,2,3]
sum(list)

>>> 6

使用num_clothes.append()更改为列表,并在while循环的每次迭代中向列表添加整数

或只需num_clothes

即可使+= int(input(..etc))成为总数