[英]How do I separate the numbers from an input in order to add them?
我正在尝试让用户输入一系列数字(用逗号分隔)以接收它们的总数。
我已经尝试过(没有运气):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
如果用户输入5.5、6、5.5,则预期输出为17。
你快到了。
拆分后,值仍然是字符串,因此您必须将它们映射为浮点型。
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
输出:
The total sum is: 17.0
旁注:请不要命名您的变量list
或sum
,否则您将隐藏python内置函数!
当您split
用逗号值放入一个列表,你需要将它们从字符串转换为数字。 你可以这样做
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
有关参考,请参见Python中的列表推导 。
(此外,您不应该将list
用作变量名,因为那是Python中的函数。)
您必须将输入转换为float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
您必须先转换为数字,然后再将它们加在一起。
例如,您可以将它们全部转换为float
:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
很难知道错误\\输出代码的示例出了什么问题。
我认为问题是当它是字符串列表时,获取列表的总和(非常糟糕的名字)。
请尝试以下
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
期望整数时,此代码将起作用,如果要使用浮点数,请更改列表理解。
尽量不要使用与标准对象相同的名称来命名对象,例如list,int,str,float等。
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
输出:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
在下面使用
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.