Pythonic的方式將使用itertools.product
,因爲它返回傳遞給它的迭代的笛卡爾乘積。由於沒有Python的循環涉及這將是比較快於版本正在使用循環:
>>> arr = np.dstack(np.meshgrid(a, b)).reshape(-1, 2)
>>> np.subtract(arr[:,0], arr[:,1])
array([-3, -2, -1, -4, -3, -2, -5, -4, -3])
時機比較:
>>> from operator import sub
>>> from itertools import starmap, product
>>> list(starmap(sub, product(a, b)))
[-3, -4, -5, -2, -3, -4, -1, -2, -3]
在NumPy的,你可以用提到here食譜做到這一點
>>> b = [4, 5, 6]*1000
>>> a = [1, 2, 3]*1000
>>> %timeit list(starmap(sub, product(a, b)))
1 loops, best of 3: 464 ms per loop
>>> %timeit [x - y for x in a for y in b]
1 loops, best of 3: 491 ms per loop
>>> %%timeit
result = []
for x in a:
for y in b:
result.append(x - y) #attribute lookup is slow
...
1 loops, best of 3: 908 ms per loop
>>> %%timeit
result = [];append = result.append
for x in a:
for y in b:
append(x - y)
...
1 loops, best of 3: 617 ms per loop
#Numpy version will be little faster if a and b were nd arrays.
>>> %timeit arr = np.dstack(np.meshgrid(a, b)).reshape(-1, 2);np.subtract(arr[:,0], arr[:,1])
1 loops, best of 3: 573 ms per loop
你已經提供了你的整個代碼 – 2014-11-04 13:27:47
而不是讓它更「pythonic」,這是一個荒謬的想法,使這個代碼更容易閱讀。首先讓變量名稱的方式更有意義。 – 2014-11-04 13:27:56
@Puciek不明白你的意思,因爲我很清楚。我不是,糾正我。 – DimKoim 2014-11-04 13:33:08