Getting the Product of a Python List

撰写于 2018-08-11 修改于 2018-08-11 分类 Python 标签 Python

Given a list, get the product of the list, for example a list [1, 2, 3] and its product is 1*2*3=6.

1
2
3
>>> a = [1, 2, 3]
>>> get_product(a)
6

Method 1

Using numpy‘s prod

Method 2

Using functools.reduce and operator.mul

1
2
3
4
5
6
>>> a = [1, 2, 3]
>>> import functools
>>> import operator
>>> b = functools.reduce(operator.mul, a, 1)
>>> b
6

Reference

Site by GoingMyWay using Hexo & Random
备案号: 粤ICP备16087705号-1

I am a ML and RL research student

Hide