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
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(',')]
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
。这自然不起作用,因为一次只能转换一个数字。例如,int('45')
将起作用,但int('12 34, 56')
将不起作用。我想你应该这样做:
这不是最简洁的答案,但我认为它可以让你更好地理解。紧实感会在以后出现。
您没有创建列表。您正在使用用户输入创建一个字符串,并试图将该字符串转换为int
你可以这样做:
输出:
我做了什么?
我把你的第一行改成:
它接受用户的输入作为逗号分隔的字符串。然后,它将该字符串中的每个元素转换为int。它通过在每个逗号处的字符串上使用^{} 来完成此操作。
如果用户输入一个非整数或不使用逗号分隔输入,则此方法将失败。
正确的做法是:
若要求和,需要将空格分隔的字符分别转换为
int
字符,如上所述,使用map函数。相关问题 更多 >
编程相关推荐