返回列表的乘积 您所在的位置:网站首页 python乘积 返回列表的乘积

返回列表的乘积

2023-03-23 12:57| 来源: 网络整理| 查看: 265

回答问题

是否有更简洁、有效或简单的 Python 方式来执行以下操作?

def product(lst): p = 1 for i in lst: p *= i return p

编辑:

我实际上发现这比使用 operator.mul 稍微快一点:

from operator import mul # from functools import reduce # python3 compatibility def with_lambda(lst): reduce(lambda x, y: x * y, lst) def without_lambda(lst): reduce(mul, lst) def forloop(lst): r = 1 for x in lst: r *= x return r import timeit a = range(50) b = range(1,50)#no zero t = timeit.Timer("with_lambda(a)", "from __main__ import with_lambda,a") print("with lambda:", t.timeit()) t = timeit.Timer("without_lambda(a)", "from __main__ import without_lambda,a") print("without lambda:", t.timeit()) t = timeit.Timer("forloop(a)", "from __main__ import forloop,a") print("for loop:", t.timeit()) t = timeit.Timer("with_lambda(b)", "from __main__ import with_lambda,b") print("with lambda (no 0):", t.timeit()) t = timeit.Timer("without_lambda(b)", "from __main__ import without_lambda,b") print("without lambda (no 0):", t.timeit()) t = timeit.Timer("forloop(b)", "from __main__ import forloop,b") print("for loop (no 0):", t.timeit())

给我

('with lambda:', 17.755449056625366) ('without lambda:', 8.2084708213806152) ('for loop:', 7.4836349487304688) ('with lambda (no 0):', 22.570688009262085) ('without lambda (no 0):', 12.472226858139038) ('for loop (no 0):', 11.04065990447998) Answers

不使用 lambda:

from operator import mul # from functools import reduce # python3 compatibility reduce(mul, list, 1)

它更好更快。使用 python 2.7.5

from operator import mul import numpy as np import numexpr as ne # from functools import reduce # python3 compatibility a = range(1, 101) %timeit reduce(lambda x, y: x * y, a) # (1) %timeit reduce(mul, a) # (2) %timeit np.prod(a) # (3) %timeit ne.evaluate("prod(a)") # (4)

在以下配置中:

a = range(1, 101) # A a = np.array(a) # B a = np.arange(1, 1e4, dtype=int) #C a = np.arange(1, 1e5, dtype=float) #D

python 2.7.5 的结果

| 1 | 2 | 3 | 4 |

-------+-----------+------------+-----------+------ -----+

A 20.8 μs 13.3 μs 22.6 μs 39.6 μs

B 106 μs 95.3 μs 5.92 μs 26.1 μs

C 4.34 毫秒 3.51 毫秒 16.7 微秒 38.9 微秒

D 46.6 毫秒 38.5 毫秒 180 微秒 216 微秒

结果:np.prod是最快的,如果你使用np.array作为数据结构(小数组18x,大数组250x)

使用 python 3.3.2:

| 1 | 2 | 3 | 4 |

-------+-----------+------------+-----------+------ -----+

A 23.6 μs 12.3 μs 68.6 μs 84.9 μs

B 133 μs 107 μs 7.42 μs 27.5 μs

C 4.79 毫秒 3.74 毫秒 18.6 微秒 40.9 微秒

D 48.4 毫秒 36.8 毫秒 187 微秒 214 微秒

python 3慢吗?



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有