【问题标题】:Can you for loop completely through a range, but starting from the nth element?你可以完全循环一个范围,但从第 n 个元素开始?
【发布时间】:2018-12-09 20:49:37
【问题描述】:

我想知道是否存在执行此类操作的基本解决方案:

for n in range(length=8, start_position= 3, direction= forward)

我遇到的问题是我希望循环继续通过最终索引,然后在 idx = 0、然后 idx = 1 等处重新开始,并在 idx = 3、start_position 处停止。

为了给出上下文,我寻求 n-queen 问题的所有可能的完整解决方案。

【问题讨论】:

  • 你的意思是range(3, 3+8)
  • 你看过range的文档吗?
  • timegb- 是范围的第二个参数等于 11 吗?

标签: python discrete-mathematics


【解决方案1】:

根据您的最新编辑,您需要一个“正常”范围和模运算符:

for i in range(START, START + LEN): 
    do_something_with(i % LEN)

【讨论】:

    【解决方案2】:
    from itertools import chain
    
    for n in chain(range(3,8), range(3)):
        ...
    

    chain() 返回一个带有3, 4, ..., 7, 0, 1, 2 的迭代器

    【讨论】:

    • 很像!
    【解决方案3】:

    解决这个问题的另一个选择是使用模运算。你可以这样做,例如:

    for i in range(8)
       idx = (i + 3) % 8
       # use idx
    

    这很容易推广到使用不同的长度和偏移量。

    【讨论】:

      【解决方案4】:
      def loop_around_range(length, start_position, direction='forward'):
          looped_range = [k % length for k in range(start_position, start_position+length)]
          if direction == 'forward':
               return looped_range
          else:
               return looped_range[::-1]
      

      【讨论】:

        【解决方案5】:

        您可以使用itertools.cycle 为任意迭代实现此功能。

        from itertools import cycle
        
        def circular_iterator(iterable, skip=0, length=None, reverse=False):
            """Produces a full cycle of @iterable@, skipping the first @skip@ elements
            then tacking them on to the end.
        
            if @iterable@ does not implement @__len__@, you must provide @length@
            """
        
            if reverse:
                iterable = reversed(iterable)
        
            cyc_iter = cycle(iterable)
            for _ in range(skip):
                next(cyc_iter, None)
        
            if length:
                total_length = length
            else:
                total_length = len(iterable)
        
            for _ in range(total_length):
                yield next(cyc_iter, None)
        
        >>> lst = [x for x in range(1, 9)]
        # [1, 2, 3, 4, 5, 6, 7, 8]
        
        >>> list(circular_iterator(lst, skip=3))
        [4, 5, 6, 7, 8, 1, 2, 3]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-28
          • 2014-03-16
          • 1970-01-01
          • 2019-08-27
          • 2020-12-29
          • 1970-01-01
          相关资源
          最近更新 更多