我想做的是按顺序从列表中减去所有项:
>>> ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
>>> 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 # should be computed
-53
>>> ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
>>> 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 # should be computed
-53
reduce()
函数:>>> from functools import reduce
>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> reduce(lambda x, y: x - y, lst)
-53
operator.sub
而不是 lambda
:>>> import operator
>>> reduce(operator.sub, lst)
-53
reduce()
是一个内置函数,所以您不需要导入它。result = ListOfNumbers[0]
for n in ListOfNumbers[1:]:
result -= n
result = ListOfNumbers[0] - sum(ListOfNumbers[1:])
ListOfNumbers[0] - sum(ListOfNumbers[1:])
呢? - undefineditertools.accumulate
和 operator.sub
函数:import itertools, operator
l = [1,2,3,4,5,6,7,8,9,10]
print(list(itertools.accumulate(l, operator.sub))[-1]) # -53
这并不意味着比已发布的functools.reduce()
解决方案更好,但它提供了一个额外的功能——每对数字进行减法运算时都能得到中间结果(第一项作为起始点):
[1, -1, -4, -8, -13, -19, -26, -34, -43, -53]
if len(items) == 0:
print(0)
elif len(items) == 1:
print(items[0])
else:
print(items[0] - sum(items[1:]))
operator.sub
? - undefinedoperator.sub
。我猜,它甚至可能稍微更高效一些。 - undefined