如何用Python减去列表中的所有项?

2024-10-01 15:45:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是按顺序减去列表中的所有项目:

>>> 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

Tags: 项目列表顺序beshouldcomputedlistofnumbers
3条回答

使用itertools.accumulateoperator.sub函数:

import itertools, operator

l = [1,2,3,4,5,6,7,8,9,10]
print(list(itertools.accumulate(l, operator.sub))[-1])   # -53

这并不是说它比posted functools.reduce()解决方案更好,而是提供了一个额外的功能-每个对的中间减法结果(第一项保留为起点):

^{pr2}$

可以迭代数组并减去:

result = ListOfNumbers[0]
for n in ListOfNumbers[1:]:
    result -= n

或者,正如vaultah指出的:

^{pr2}$

您可以使用^{}函数:

>>> from functools import reduce
>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> reduce(lambda x, y: x - y, lst)
-53

或者使用^{}代替lambda

^{pr2}$

注意,在python2.x中^{}是一个内置的,所以不需要导入它。在

相关问题 更多 >

    热门问题