是否有更簡潔,高效或簡單的pythonic方式來執行以下操作?返回列表的產品
def product(list):
p = 1
for i in list:
p *= i
return p
編輯:
其實我覺得這是略高於使用operator.mul快:
from operator import mul
# from functools import reduce # python3 compatibility
def with_lambda(list):
reduce(lambda x, y: x * y, list)
def without_lambda(list):
reduce(mul, list)
def forloop(list):
r = 1
for x in list:
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)
的零結果不是很有趣。有趣的是你在什麼平臺上使用的是什麼版本的Python。 – 2010-01-21 22:46:34
不 - 我只是添加了零,因爲我意識到wiso的答案包括零,我想知道它有多大的差異。 我在ubuntu 9.10上使用python 2.6.4。 – 2010-01-21 23:05:43
這裏給出的選項之間有一個功能差異,對於一個空列表,'reduce'應答引發一個'TypeError',而'for'循環應答返回1.這是'for'循環應答中的一個錯誤(一個空列表的產品不會超過17或'犰狳')。 – 2010-01-24 08:28:02