【问题标题】:How to loop over a circular list, while peeking ahead and behind current element?如何在循环列表中循环,同时查看当前元素的前后?
【发布时间】:2012-08-17 17:56:33
【问题描述】:

使用以下示例列表:L = ['a','b','c','d']

我想实现以下输出:

>>> a d b
>>> b a c
>>> c b d
>>> d c a

伪代码是:

for e in L:
    print(e, letter_before_e, letter_after_e

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以只循环 L 并将索引 i 减去和加上 1 模 len(L) 来获取上一个和下一个元素。

    【讨论】:

      【解决方案2】:

      你已经差不多了

      for i, e in enumerate(L):
          print(e, L[i-1], L[(i+1) % len(L)])
      

      编辑添加模组

      【讨论】:

      • 您将遇到超出范围的问题。因为 [3+1] 超出范围。
      【解决方案3】:

      在这种情况下可能有点矫枉过正,但这是循环双向链表http://ada.rg16.asn-wien.ac.at/~python/how2think/english/chap17.htm的一般用例@

      【讨论】:

        【解决方案4】:

        从概念上讲,跟踪您已经看到的项目通常比向前看更简单。 deque 类非常适合跟踪 n 以前的项目,因为它允许您设置最大长度;添加新项目会自动将旧项目推开。

        from collections import deque
        
        l = ['a','b','c','d']
        d = deque(l[-2:], maxlen=3)
        
        for e in l:
            d.append(e)
            print d[1], d[0], d[2]
        

        此解决方案的唯一区别是d c a 将首先出现而不是最后出现。如果这很重要,您可以开始时就好像您已经看过一次迭代一样:

        from collections import deque
        
        l = ['a','b','c','d']
        d = deque(l[-1:] + l[:1], maxlen=3)
        
        for e in l[1:] + l[:1]:
            d.append(e)
            print d[1], d[0], d[2]
        

        【讨论】:

          【解决方案5】:

          在我的代码中,我将在列表中使用 3 个元素的 moving window ,该列表由最后一个元素添加并由第一个元素添加:

          from itertools import tee, izip, chain
          
          def window(iterable,n):
              '''Moving window
              window([1,2,3,4,5],3) -> (1,2,3), (2,3,4), (3,4,5)
              '''
              els = tee(iterable,n)
              for i,el in enumerate(els):
                  for _ in range(i):
                      next(el, None)
              return izip(*els)
          
          
          def chunked(L):
              it = chain(L[-1:], L, L[:1]) # (1,2,3,4,5) -> (5,1,2,3,4,5,1)
              for a1,a2,a3 in window(it,3): # (3,1,2,3,1) -> (3,1,2), (1,2,3), (2,3,1)
                  yield (a2,a1,a3)
          
          
          ## Usage example ##
          L = ['a','b','c','d']
          
          for t in chunked(L):
              print(' '.join(t))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-09-05
            • 1970-01-01
            • 1970-01-01
            • 2023-04-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多