【问题标题】:Construct a circular loop in python [duplicate]在python中构造一个循环[重复]
【发布时间】:2013-09-10 00:36:50
【问题描述】:

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

L[0],L[1]

L[1],L[2]

L[2],L[0]

有没有一种简单的方法可以得到稍微不同的输出

L[0],L[1]

L[1],L[2]

L[0],L[2]

【问题讨论】:

  • 反向上当只是因为其他帖子有更好的答案。如有争议,请在此处或Python聊天室联系我

标签: python arrays cyclic


【解决方案1】:

使用模运算符

>>> 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)

至于你的输出,你可以这样做。

>>> 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

【讨论】:

  • itertools.cycle 很有趣!虽然来自docs:“注意,工具包的这个成员可能需要大量的辅助存储(取决于可迭代的长度)。”
【解决方案2】:

你可以只使用递增索引,并使用模(除法的余数)

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

将产生:

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

【讨论】:

    【解决方案3】:

    你可以试试

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

    输出

    1 2
    2 3
    3 1
    

    这样,您可以执行xrange(10) 之类的操作,并且仍然可以循环:

    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】:

        itertools documentation 中有一个食谱可以使用:

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

        使用itertools.cycle(L) 拨打此电话,您就可以开始了:

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

        【讨论】:

          【解决方案6】:

          您是说组合吗? http://en.wikipedia.org/wiki/Combination

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

          您可以使用 then 进行排序

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

          输出:

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

          【讨论】:

            猜你喜欢
            • 2014-10-31
            • 2018-10-12
            • 2018-12-06
            • 2023-03-24
            • 1970-01-01
            • 2012-11-27
            • 1970-01-01
            • 2023-02-06
            • 1970-01-01
            相关资源
            最近更新 更多