[英]Writing a custom sum function that sums a list of numbers
我是 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 中的 for 循环非常容易使用。 对于您的应用程序,如下所示:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
编辑:是的,我很慢。 另一个答案可能更有帮助。 ;)
这适用于 python 3.x,类似于 Adam Smith 解决方案
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
您甚至可以编写一个函数,该函数可以对列表中嵌套列表中的元素进行求和。 例如它可以求和[1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
对于my_sum([1, 2, [1, 2, [1, 2]]])
输出将为9
。
如果您为此任务使用标准内置函数sum
,它将引发TypeError
。
这是一个有点慢的版本,但效果很好
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
这应该很好用
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
使用 accumulator 函数初始化 accumulator 变量 (runTotal) 值为 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
打印 sumTo(15) #outputs 120
如果您使用的是Python 3.0.1
或更高版本,则使用以下代码使用reduce
对数字/整数列表进行求和
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper): sumlist=0 for x in arr: sumlist+=x return sumlist
这里函数addelements
接受 list 并返回该列表中所有元素的总和,仅当传递给函数addelements
的参数是list
并且该列表中的所有元素都是integers
。 否则函数将返回消息“不是列表或列表没有所有整数元素”
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
输出:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.