Zip lists in Python

前端 未结 10 2080
无人及你
无人及你 2020-11-22 02:09

I am trying to learn how to \"zip\" lists. To this end, I have a program, where at a particular point, I do the following:

x1, x2, x3 = stuff.calculations(wi         


        
10条回答
  •  无人共我
    2020-11-22 02:27

    It's worth adding here as it is such a highly ranking question on zip. zip is great, idiomatic Python - but it doesn't scale very well at all for large lists.

    Instead of:

    books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
    words = [345, 567, ... , 672]
    
    for book, word in zip(books, words):
       print('{}: {}'.format(book, word))
    

    Use izip. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i:

    for book, word in izip(books, words):
       print('{}: {}'.format(book, word))
    

提交回复
热议问题