Python 从一个循环的中间迭代到开始之前
Python iterating from the middle of a cycle to before the start
我一直在编写棋盘游戏来练习 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 开始循环,然后循环遍历其余的一次?
这样的事情怎么样?
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
中拼凑出一些东西
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()
。
我一直在编写棋盘游戏来练习 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 开始循环,然后循环遍历其余的一次?
这样的事情怎么样?
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
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()
。