如何划分列表中的所有项目

时间:2017-09-22 16:34:14

标签: python list division

>>> ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
>>> 1 / 2 / 3 / 4 / 5 / 6 / 7 / 8 / 9 / 10  # should be computed
2.75573192e

2 个答案:

答案 0 :(得分:2)

您可以使用reduce

ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
print(reduce(lambda x, y: x/float(y), ListOfNumbers))

输出:

2.7557319224e-07 

您还可以将itertools.accumulate用于Python3:

import operator
import itertools
print(list(itertools.accumulate(ListOfNumbers, func=operator.truediv))[-1])

输出:

2.7557319223985894e-07

答案 1 :(得分:2)

您可以使用除法运算reduce列表。请注意,由于列表中的所有元素都是整数,因此您必须将它们转换为浮点数才能使用浮点除法并获得您期望的结果:

result = reduce((lambda x, y: float(x) / y), [1,2,3,4,5,6,7,8,9,10])
相关问题