Using list comprehension in Python to do something similar to zip()?

后端 未结 5 1240
暖寄归人
暖寄归人 2021-02-04 14:05

I\'m a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it\'s a pretty powerful feature that\'s worth learning.

5条回答
  •  忘了有多久
    2021-02-04 14:16

    This takes zip's output and converts all tuples to lists:

    map(list, zip(cities, airports))
    

    As for the performance of each:

    $ python -m timeit -c '[ [a, b] for a, b in zip(xrange(100), xrange(100)) ]'
    10000 loops, best of 3: 68.3 usec per loop
    
    $ python -m timeit -c 'map(list, zip(xrange(100), xrange(100)))'
    10000 loops, best of 3: 75.4 usec per loop
    
    $ python -m timeit -c '[ list(x) for x in zip(range(100), range(100)) ]'
    10000 loops, best of 3: 99.9 usec per loop
    

提交回复
热议问题