我是 Python 的新手,需要一些帮助来编写一个将列表作为参数的函数。
我希望用户能够输入数字列表(例如 [1,2,3,4,5]),然后让我的程序对列表的元素求和。但是,我想使用 for 循环对元素求和,而不仅仅是使用内置的 sum
函数。
我的问题是我不知道如何告诉解释器用户正在输入列表。当我使用这段代码时:
def sum(list):
它不起作用,因为解释器只需要从 sum 中获取的一个元素,但我想输入一个列表,而不仅仅是一个元素。我尝试使用 list.append(..),但无法按照我想要的方式工作。
感谢期待!
编辑:我正在寻找这样的东西(感谢“irrenhaus”):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
最佳答案
我不确定您是如何构建“用户输入列表”的。你在使用循环吗?是纯输入吗?你是从 JSON 还是 pickle 读取?这是一个很大的未知数。
假设您想让他们输入以逗号分隔的值,只是为了获得答案。
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
前三行有点难看。您可以组合它们:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
但这也有点丑陋。怎么样:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
关于python - 编写一个对数字列表求和的自定义求和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296807/