简体   繁体   English

如何优雅地在Python中创建双向for循环?

[英]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? 与外部范围变量一样,如何使用相同的循环循环获取第一个元素前进一个var和另一个var后一个元素后退? Is there a function similar to enumerate that returns two vars 是否存在类似于枚举的函数,返回两个变量

you could zip one iterator and its reverse: 你可以zip一个迭代器及其反转:

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 但是,对于生成器,您必须强制迭代到list因为reverse需要一个序列

TypeError: argument to reversed() must be a sequence

list , tuple or range are OK. listtuplerange都可以。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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