在python中构建循环 [英] Construct a circular loop in python

查看:78
本文介绍了在python中构建循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想循环遍历一个列表。
ex:我在数组L中有三个元素= [1,2,3]
我想获得输出为

I want to loop a list over a cycle. ex: I have three elements in the array L = [1,2,3] I want to get the output as

L [ 0],L [1]

L[0],L[1]

L [1],L [2]

L[1],L[2]

L [2] ,L [0]

L[2],L[0]

有没有一种简单的方法来获得略有不同的输出

Is there a easy way get the slightly different output

L [, L [1]

L[0],L[1]

L [1],L [2]

L[1],L[2]

L [0],L [ 2]

L[0],L[2]

推荐答案

使用模运算符

>>> a = [1,2,3]
>>> for x in range(10):
        print a[x % len(a)]

使用 itertools.cycle

>>> iterator = cycle(a)
>>> for _ in range(10):
        print next(iterator)

至于您的输出,您可以执行此操作。

As for your output, you could just do this.

>>> for x in range(10):
        print '{0}, {1}'.format(a[x % len(a)], a[(x+1) % len(a)])

>>> 1, 2
>>> 2, 3
>>> 3, 1
... etc etc

这篇关于在python中构建循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆