Saving iterator from python's zip

后端 未结 2 1007
自闭症患者
自闭症患者 2021-01-24 02:34

So, I have a function that I have to call a ton of times. That function iterates through a list by pairs like so:

for a, b in zip(the_list, the_list[1:]):
    #          


        
2条回答
  •  暖寄归人
    2021-01-24 03:20

    You can buffer a generator to a list like so:

    z = list(zip(x, y))
    

    However, I doubt there'll be much performance benefit in this, since zip is itself just iterating over its arguments, which is what you'd end up doing if you buffered it to a list. There's not really much "computation" going on when you call zip.

    Edit: This assumes you're using Python 3, wherein zip really does return a generator. In Python 2, zip returns a list, so you're probably better off reusing this list between function calls.

提交回复
热议问题