Nonostante *zip
sia più Pythonic, il codice seguente ha prestazioni molto migliori:
xs, ys = [], []
for x, y in zs:
xs.append(x)
ys.append(y)
Inoltre, quando l'elenco originale zs
è vuoto, *zip
verrà generato, ma questo codice può essere gestito correttamente.
Ho appena eseguito un rapido esperimento ed ecco il risultato:
Using *zip: 1.54701614s
Using append: 0.52687597s
Eseguendolo più volte, append
è 3 volte - 4 volte più veloce di zip
! Lo script di test è qui:
#!/usr/bin/env python3
import time
N = 2000000
xs = list(range(1, N))
ys = list(range(N+1, N*2))
zs = list(zip(xs, ys))
t1 = time.time()
xs_, ys_ = zip(*zs)
print(len(xs_), len(ys_))
t2 = time.time()
xs_, ys_ = [], []
for x, y in zs:
xs_.append(x)
ys_.append(y)
print(len(xs_), len(ys_))
t3 = time.time()
print('Using *zip:\t{:.8f}s'.format(t2 - t1))
print('Using append:\t{:.8f}s'.format(t3 - t2))
La mia versione di Python:
Python 3.6.3 (default, Oct 24 2017, 12:18:40)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(1, 3, 5)
e(2, 4, 6)
non elenchi. dovresti usaremap(list, zip(*[(1, 2), (3, 4), (5, 6)]))