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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29803390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:02:17  来源:igfitidea点击:

How to get a list of numbers as input and calculate the sum?

pythonsum

提问by Eliza

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

回答by ZdaR

Correct way of doing the same is:

正确的做法是:

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

To find the sum you need to convert the space separated characters into intindividuallyas done above using mapfunction.

为了找到你需要转换的空间分隔字符集和int个别上面使用为已完成的地图功能。

回答by Andy

You are not creating a list. You are creating a string with your user input and attempting to convert that string to an int.

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

You can do something like this:

你可以这样做:

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

Output:

输出:

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


What did I do?

我做了什么?

I changed your first line into:

我把你的第一行改成了:

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

This accepts the user's input as a comma separated string. It then converts every element in that string into an int. It does this by using spliton the string at each comma.

这接受用户的输入作为逗号分隔的字符串。然后它将该字符串中的每个元素转换为 int。它通过split在每个逗号处的字符串上使用来做到这一点。

This method will fail if the user inputs a non-integer or they don't comma separate the input.

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

回答by Totem

It appears you are attempting to convert a string of numbers that most likely looks like this(you never specified input format):

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

"1 23 4 45 4"

OR this

或这个

"1, 45, 65, 77"

to an int. This naturally won't work as only one number at a time could be converted like this. For instance int('45')will work, but int('12 34, 56')will not.

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

I think what you need to do is something like this:

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

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

This isn't the most compact answer, but I think it breaks it down for you to better understand. Compactness can come later.

这不是最简洁的答案,但我认为它分解了它以便您更好地理解。紧凑性可以稍后出现。

回答by marmeladze

if you want to store numbers in list, create list. also add a loop for user enters values. you can assign an input to break the loop or add a counter.

如果要将数字存储在列表中,请创建列表。还为用户输入值添加一个循环。您可以分配一个输入来中断循环或添加一个计数器。

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)  

or without list

或没有列表

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

result

结果

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