【问题标题】:Python iterating from the middle of a cycle to before the startPython从循环中间迭代到开始之前
【发布时间】:2016-09-05 21:23:29
【问题描述】:

我一直在编写一个棋盘游戏来练习 Python。我用一个循环来做这样的转弯顺序:

turncycle = [0,1,2,3]
for turnindex in cycle(turncycle):
    #.
    #...turn stuff
    #...turnindex is used for active player
    #.

我想要做的是给定一个回合索引,开始一个迷你回合,事件卡触发并且他们必须做一些事情。有没有办法重建列表,以便我可以将 [0,1,2,3] 更改为 [1,2,3,0] 或从 1,2 或 3 开始循环,然后在其余部分循环一次?

【问题讨论】:

  • turncycle[1:]+[turncycle[0]] 也许?
  • 或使用 numpynp.roll(turncycle, 1)
  • 不确定你的意思。期望行为的示例会很好。

标签: python list iteration cycle


【解决方案1】:

这样的事情呢?

def next_cycle(lst):
    return turncycle[1:] + turncycle[:1]

turncycle = [0, 1, 2, 3]

for turnindex in range(len(turncycle)):
    turncycle = next_cycle(turncycle)
    print turncycle

【讨论】:

  • Imho turncycle[1:] + turncycle[:1] 看起来好多了,而且很容易概括。
【解决方案2】:

拼凑来自itertools recipes的东西

import itertools
a = [0,1,2,3,4,5,6,7]
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(itertools.islice(iterator, n, n), None)

def cycle(turncycle, start = 0):
    # limit to the original number of turns
    no_of_turns = len(turncycle)
    # make a non-ending cycle
    turncycle = itertools.cycle(turncycle)
    # advance to the start position
    consume(turncycle, start)
    # return a new turn cycle - from the itertools take() recipe
    return itertools.islice(turncycle, no_of_turns)

>>> 
>>> for n in cycle(a):
    print(n),

0 1 2 3 4 5 6 7
>>> for n in cycle(a, 4):
    print(n),

4 5 6 7 0 1 2 3
>>> for n in cycle(a, 20):
    print(n),

4 5 6 7 0 1 2 3
>>>

cycle 可能需要稍作调整,具体取决于您认为 start 参数的含义。

它可能被重命名为roll()

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2021-08-09
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2010-12-09
    相关资源
    最近更新 更多