python - 如何将列表中的所有整数相乘? - Python

标签 python multiplication

list1= [1,2,3,4] 

1) 我想将此列表中的每个元素相乘以输出 24。如何在 python 中执行此操作而不使用 for 循环?是否有内置库可以执行此操作?

2) 如果 list1 包含如下字符串怎么办

list1= ["1,2,3,4"]

3) 如果 list1 包含如下字符串怎么办

list1 = ['1234']

最佳答案

您还可以使用:

import operator
reduce(operator.mul, [1,2,3,4])

出局:

24

至于性能,使用 operator.mul 会更快一些:

In [1]: from operator import mul

In [2]: lst = [1,2,3,4]

In [3]: reduce(mul,lst)
Out[3]: 24

In [4]: %timeit reduce(mul,lst)
1000000 loops, best of 3: 733 ns per loop

In [5]: %timeit reduce(lambda x,y:x*y,lst)
1000000 loops, best of 3: 1.28 us per loop

如果您将数字作为字符串:

In [6]: reduce(mul,map(int,["1,2,3,4"][0].split(',')))
Out[6]: 24

对于大型列表,您还可以使用返回迭代器的 itertools.imap:

In [7]: from itertools import imap

In [8]: %timeit reduce(mul,imap(int,["1,2,3,4"][0].split(',')*10000))
1 loops, best of 3: 264 ms per loop

编辑: 希望你最后的编辑:

In [18]: reduce(mul,map(int,['1234'][0]))
Out[18]: 24

关于python - 如何将列表中的所有整数相乘? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14453017/

相关文章:

python - cqlsh连接错误: 'ref() does not take keyword arguments'

python 测试我的方法

Java - 图像着色

c++ - 如何避免指针运算中的乘法?

c - 将数组的每个元素乘以C中的数字

Python 2.6.7 未在 Windows 中初始化

python - 在 Python 中用名称绘制 (x,y) 坐标

python - Choropleth map 不为国家着色?

matlab - 两个张量之间的克罗内克积

python - 快速将 Pandas 列乘以年度系数