How to split all items in a list together

For instance:

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

I want to do:

1/2/3/4/5/6

I tried using a function operator.div, but it does not seem to give the correct result. By the way, I'm pretty new to python.

+4
source share
3 answers

You can use reduce.

Apply the function of two arguments cumulatively to elements of a sequence from left to right 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

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

As truedivalready demonstrated by another answer, this is an alternative (preferably another option) for Python2

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

reduce() operator.truediv:

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

. python3.x reduce() functools.

+6

?

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

All Articles