Construct a circular loop in python [duplicate]

丶灬走出姿态 提交于 2019-12-11 16:43:10

问题


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[1],L[2]

L[2],L[0]

Is there a easy way get the slightly different output

L[0],L[1]

L[1],L[2]

L[0],L[2]


回答1:


Using modulus operator

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

Using 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



回答2:


You can just use increasing index, and use modulo (remainder of division)

myList = [1,2,3]
for i in xrange(len(myList)):
    myTuple = (myList[i],myList[(i+1)%len(myList)])
    print myTuple

will produce:

(1,2)
(2,3)
(3,1)



回答3:


You could try something like

L = [1,2,3]
length = len(L)
for i in xrange(length):
        print L[i % length], L[(i+1) % length]

Output

1 2
2 3
3 1

This way, you can do something like xrange(10) and still have it cycle:

1 2
2 3
3 1
1 2
2 3
3 1
1 2
2 3
3 1
1 2



回答4:


l = [0,1,2,3]
for i in xrange(0, len(l)):
    print l[i], l[(i+1) % len(l)]


0 1
1 2
2 3
3 0



回答5:


There is a recipe in the itertools documentation that you can use:

import itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

Call this with itertools.cycle(L) and you're good to go:

L = [1, 2, 3]
for pair in pairwise(itertools.cycle(L)):
    print pair
# (1, 2)
# (2, 3)
# (3, 1)
# (1, 2)
# ...



回答6:


Did you mean combinations? http://en.wikipedia.org/wiki/Combination

from itertools import combinations
comb = []
for c in combinations([1, 2, 3], 2):
    print comb.append(c)

For sorting you can use then

sorted(comb, key=lambda x: x[1])

Output:

[(1, 2), (1, 3), (2, 3)]


来源:https://stackoverflow.com/questions/18648824/construct-a-circular-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!