Zip with list output instead of tuple
You almost had the answer yourself. Don't use map
instead of zip
. Use map
AND zip
.
You can use map along with zip for an elegant, functional approach:
list(map(list, zip(a, b)))
zip
returns a list of tuples. map(list, [...])
calls list
on each tuple in the list. list(map([...])
turns the map object into a readable list.
I love the elegance of the zip function, but using the itemgetter() function in the operator module appears to be much faster. I wrote a simple script to test this:
import timefrom operator import itemgetterlist1 = list()list2 = list()origlist = list()for i in range (1,5000000): t = (i, 2*i) origlist.append(t)print "Using zip"starttime = time.time()list1, list2 = map(list, zip(*origlist))elapsed = time.time()-starttimeprint elapsedprint "Using itemgetter"starttime = time.time()list1 = map(itemgetter(0),origlist)list2 = map(itemgetter(1),origlist)elapsed = time.time()-starttimeprint elapsed
I expected zip to be faster, but the itemgetter method wins by a long shot:
Using zip6.1550450325Using itemgetter0.768098831177