如何将列表中的所有元素划分在一起 [英] How to divide all the elements in a list together

查看:77
本文介绍了如何将列表中的所有元素划分在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

我想做

1/2/3/4/5/6

我尝试使用operator.div函数,但似乎无法给出正确的结果.顺便说一下,我是python的新手.

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.

推荐答案

您可以使用

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.

该代码可以显示为

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

等效于

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


由于truediv已经由其他答案进行了演示,因此这是一种替代方法(首选其他方法)for Python2


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

这篇关于如何将列表中的所有元素划分在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆