-7

如何创建一个将给定列表中的所有数字相加的函数?在 Python 中。像这样的东西:

list = [8, 5, 6, 7, 5, 7]

def sum(list):
    ???
4

2 回答 2

3

严格回答您的要求:

# notice how I've named it 'lst' not 'list'—'list' is the built in; don't override that
def sum(lst):  
    ret = 0
    for item in lst;
        ret += item
    return ret

或者,如果您喜欢函数式编程:

def sum(lst):
    return reduce(lambda acc, i: acc + i, lst, 0)

甚至:

import operator

def sum(lst):
    return reduce(operator.add, lst, 0)

你甚至可以让它在非数字输入上工作,这是内置sum()无法做到的(因为它是作为高效的 C 代码实现的),但这确实属于过度工程的范畴:

def sum(lst, initial=None):
    if initial is None:
        initial = type(lst[0])() if lst else None
    return reduce(lambda acc, i: acc + i, lst, initial)

>>> sum([1, 2, 3])
6
>>> sum(['hello', 'world'])
'hello world'
>>> sum([[1, 2, 3], [4, 5, 6]])
[1, 2, 3, 4, 5, 6]

但由于 Python 列表是无类型的,在空列表的情况下,此函数将返回None.

注意:但是,正如其他人所指出的,这仅对学习有用;在现实生活中,您使用内置sum()功能。

于 2013-09-30T13:21:17.213 回答
0

它已经存在,无需定义它:

sum([8,5,6,7,5,7])
于 2013-09-30T13:19:10.610 回答