如何获取数字列表作为输入并计算总和? [英] How to get a list of numbers as input and calculate the sum?

查看:19
本文介绍了如何获取数字列表作为输入并计算总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

正确的做法是:

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 函数.

To find the sum you need to convert the space separated characters into int individually as done above using map function.

这篇关于如何获取数字列表作为输入并计算总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆