For loops (novice)

前端 未结 5 771

I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format for x in y

5条回答
  •  鱼传尺愫
    2021-01-18 03:53

    You can use a generator expression to do this efficiently and with little excess code:

    for i in (2**x for x in range(10)): #In Python 2.x, use `xrange()`.
        ...
    

    Generator expressions work just like defining a manual generator (as in Greg Hewgill's answer), with a syntax similar to a list comprehension. They are evaluated lazily - meaning that they don't generate a list at the start of the operation, which can cause much better performance on large iterables.

    So this generator works by waiting until it is asked for a value, then asking range(10) for a value, doubling that value, and passing it back to the for loop. It does this repeatedly until the range() generator yields no more values.

提交回复
热议问题