Vâng, tôi đã thực hiện một số xét nghiệm cho python2:
import time
from operator import itemgetter
from itertools import chain, izip_longest
a = [1, 2, 3, 8, 12]
b = [2, 6, 4, 5, 6]
print "Using value and zip"
starttime = time.time()
c = [value for pair in zip(a, b[::-1]) for value in pair]
elapsed = time.time() - starttime
print c
print elapsed
print "Using chain and izip"
starttime = time.time()
c = list(chain(*izip_longest(a, b[::-1])))
elapsed = time.time() - starttime
print c
print elapsed
print "Using itemgetter"
c = []
starttime = time.time()
for i in xrange(0, len(a)):
c.append(itemgetter(i)(a))
c.append(itemgetter(len(b)-i-1)(b))
elapsed = time.time() - starttime
print c
print elapsed
đầu ra:
Using value and zip
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
1.59740447998e-05
Using chain and izip
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
3.2901763916e-05
Using itemgetter
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
1.4066696167e-05
Đôi khi phương pháp đầu tiên nhanh hơn và đôi khi là phương pháp thứ ba.
Đó là những kết quả cho các danh sách chiều dài = 1000:
Using value and zip
0.000767946243286
Using chain and izip
0.000431060791016
Using itemgetter
0.00203609466553
Như Bạn có thể xem phương pháp thứ hai được tốt hơn cho danh sách dài hơn.
Phần nào bạn gặp khó khăn với? –