如何将列表中的所有项目与Python相乘? [英] How can I multiply all items in a list together with Python?

查看:209
本文介绍了如何将列表中的所有项目与Python相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数 一个列表数字,然后将它们相乘.例子: [1,2,3,4,5,6]会给我1*2*3*4*5*6.我真的可以帮助您.

I need to write a function that takes a list of numbers and multiplies them together. Example: [1,2,3,4,5,6] will give me 1*2*3*4*5*6. I could really use your help.

推荐答案

Python 3:使用functools.reduce:

Python 3: use functools.reduce:

>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Python 2:使用reduce:

Python 2: use reduce:

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

要与2和3兼容,请使用pip install six,然后:

For compatible with 2 and 3 use pip install six, then:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

这篇关于如何将列表中的所有项目与Python相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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