简体   繁体   中英

How do you create a bidirectional for loop in Python elegantly?

As in with out outer scope variables, how do you loop getting the first element forward with one var and another var for the last element backward with the same loop? Is there a function similar to enumerate that returns two vars

you could zip one iterator and its reverse:

z = range(20,30)

for x,y in zip(z,reversed(z)):
    print(x,y)

results in:

20 29
21 28
22 27
23 26
24 25
25 24
26 23
27 22
28 21
29 20

With generators, though, you have to force iteration into a list since reverse expects a sequence

TypeError: argument to reversed() must be a sequence

list , tuple or range are OK.

g = (x for x in somefunc() if x > 0)
lst = list(g)
for x,y in zip(lst, reversed(lst)):
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM