Zip with list output instead of tuple

前端 未结 7 2001
梦毁少年i
梦毁少年i 2020-12-07 12:57

What is the fastest and most elegant way of doing list of lists from two lists?

I have

In [1]: a=[1,2,3,4,5,6]

In [2]: b=[7,8,9,10,11,12]

In [3]: z         


        
相关标签:
7条回答
  • 2020-12-07 13:56

    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 time
    from operator import itemgetter
    
    list1 = 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()-starttime
    print elapsed
    
    print "Using itemgetter"
    starttime = time.time()
    list1 = map(itemgetter(0),origlist)
    list2 = map(itemgetter(1),origlist)
    elapsed = time.time()-starttime
    print elapsed
    

    I expected zip to be faster, but the itemgetter method wins by a long shot:

    Using zip
    6.1550450325
    Using itemgetter
    0.768098831177
    
    0 讨论(0)
提交回复
热议问题