20 Ocak 2010, ÇARŞAMBA
Bir listenin ürünü iade
Daha kısa, daha verimli ya da sadece pythonic bir şekilde yapın.
def product(list):
p = 1
for i in list:
p *= i
return p
DÜZENLEME:
Aslında bu operatörü kullanarak daha biraz daha hızlı olduğunu bulmak.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())
bana verir
('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)
CEVAP
20 Ocak 2010, ÇARŞAMBA
Lambda kullanmadan:
from operator import mul
reduce(mul, list, 1)
daha iyi ve daha hızlı. Python 2.7.5 ile
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şağıdaki yapılandırma:
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 ile sonuçlanır
| 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 ms 3.51 ms 16.7 µs 38.9 µs D 46.6 ms 38.5 ms 180 µs 216 µs
Sonuç: eğer veri yapısı (küçük dizi için, 250x büyük dizi *18)* 15 * kullanıyorsanız np.prod
en hızlı biridir
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 ms 3.74 ms 18.6 µs 40.9 µs D 48.4 ms 36.8 ms 187 µs 214 µs
Python 3 yavaştır?
Bunu Paylaş:
Nasıl açılır listenin değişikliği form...
Ekleme Scala bir listenin sonuna bir e...
Nasıl birden fazla dosya bir dize aram...
Nasıl iç listenin belirli bir dizine g...
Kötü uygulama geçersiz bir yöntem için...