How to divide all the elements in a list together

2019-06-27 04:12发布

For example:

a = [1,2,3,4,5,6]

I want to do:

1/2/3/4/5/6

I have tried using the operator.div function but it doesn't seem to give the correct result. By the way, I am fairly new to python.

标签: python list
3条回答
我命由我不由天
2楼-- · 2019-06-27 04:38

You can use reduce.

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

The code can be demonstrated as

>>> from functools import reduce 
>>> l = [1,2,3,4,5,6]
>>> reduce(lambda x,y:x/y,l)
0.001388888888888889

which is equivalent to

>>> 1/2/3/4/5/6
0.001388888888888889

As truediv has already been demonstrated by the other answer, this is an alternative (the other way is preferred) for Python2

>>> from __future__ import division
>>> l = [1,2,3,4,5,6]
>>> reduce(lambda x,y:x/y,l)
0.001388888888888889
查看更多
beautiful°
3楼-- · 2019-06-27 04:38

Why not just use a loop?

>>> a = [1,2,3,4,5,6]
>>> i = iter(a)
>>> result = next(i)
>>> for num in i:
...     result /= num
...
>>> result
0.001388888888888889
>>> 1/2/3/4/5/6
0.001388888888888889
查看更多
【Aperson】
4楼-- · 2019-06-27 04:46

You can use reduce() and operator.truediv:

>>> a = [1,2,3,4,5,6]
>>> from operator import truediv
>>> 
>>> reduce(truediv, a)
0.001388888888888889

Note: In python3.x you need to import the reduce() function from from functools module.

查看更多
登录 后发表回答