如何获取数字列表作为输入并计算总和?

时间:2015-04-22 16:17:09

标签: python sum

mylist = int(raw_input('Enter your list: '))    
total = 0    
for number in mylist:    
    total += number    
print "The sum of the numbers is:", total

4 个答案:

答案 0 :(得分:7)

正确的做法是:

separator = " " #Define the separator by which you are separating the input integers.
# 1,2,3,4    => separator = ","
# 1, 2, 3, 4 => separator = ", "
# 1 2 3 4    => separator = " "

mylist = map(int, raw_input("Enter your list : ").split(separator)) 

print "The sum of numbers is: "+str(sum(mylist))

要使用map函数找到所需的总和,您需要将空格分隔的字符转换为int 单独,如上所述。

答案 1 :(得分:3)

您没有创建列表。您正在使用您的用户输入创建一个字符串,并尝试将该字符串转换为int。

您可以这样做:

mylist = raw_input('Enter your list: ')
mylist = [int(x) for x in mylist.split(',')]
total = 0    
for number in mylist:    
    total += number    
print "The sum of the numbers is:", total

输出:

Enter your list:  1,2,3,4,5
The sum of the numbers is: 15

我做了什么?

我将第一行改为:

mylist = raw_input('Enter your list: ')
mylist = [int(x) for x in mylist.split(',')]

这接受用户输入为逗号分隔的字符串。然后它将该字符串中的每个元素转换为int。它通过在每个逗号的字符串上使用split来实现此目的。

如果用户输入非整数或者他们不用逗号分隔输入,则此方法将失败。

答案 2 :(得分:2)

您似乎正在尝试转换最可能看起来像这样的数字字符串(您从未指定输入格式):

"1 23 4 45 4"

或者这个

"1, 45, 65, 77"

int。这自然不会起作用,因为一次只能转换一个数字。例如,int('45')可以使用,但int('12 34, 56')不会。

我认为你需要做的是这样的事情:

mylist = raw_input("Enter a list of numbers, SEPERATED by WHITE SPACE(3 5 66 etc.): ")
# now you can use the split method of strings to get a list
mylist = mylist.split() # splits on white space by default
# to split on commas -> mylist.split(",")

# mylist will now look something like. A list of strings.
['1', '44', '56', '2'] # depending on input of course

# so now you can do
total = sum(int(i) for i in mylist)
# converting each string to an int individually while summing as you go

这不是最紧凑的答案,但我认为它可以帮助您更好地理解它。紧凑性可以晚些。

答案 3 :(得分:1)

如果要在列表中存储数字,请创建列表。还为用户输入值添加循环。你可以指定一个输入来打破循环或添加一个计数器。

myList = []
counter = 0 
while counter<10: #change this to true for infinite (unlimited) loop. also remove counter variables
    num = raw_input("Enter numbers or (q)uit")
    if num == 'q': 
        break
    else:
        myList.append(int(num))
    counter +=1

print sum(myList)  

或没有列表

>>> while True:
...     num = raw_input("number or (q)uit")
...     if num == 'q': break
...     else:
...             total +=int(num)
... 

结果

number or (q)uit4
number or (q)uit5
number or (q)uit6
number or (q)uit7
number or (q)uit8
number or (q)uit9
number or (q)uit9
number or (q)uitq
>>> total
48