如何得到一个数字列表作为输入并计算其和?

2024-04-28 04:14:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: oftheinnumberforinputyourraw
3条回答

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

"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

这不是最简洁的答案,但我认为它可以让你更好地理解。紧实感会在以后出现。

您没有创建列表。您正在使用用户输入创建一个字符串,并试图将该字符串转换为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。它通过在每个逗号处的字符串上使用^{}来完成此操作。

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

正确的做法是:

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

若要求和,需要将空格分隔的字符分别转换为int字符,如上所述,使用map函数。

相关问题 更多 >