我试图找出如何打印以下列表,而不是从第一个项目开始。需要说明的是:如果列表为[0,1,2,3,4,5,6,7,8]
,我想打印类似4,5,6,7,8,0,1,2,3
以下是代码:
you_can_move_on = False
List = [0,1,2,3,4,5,6,7,8]
next_player = 3
while not you_can_move_on:
next_player = self.get_next_player_index(next_player)
you_can_move_on = self.check_if_I_can_move_on
print(next_player)
def get_next_player_index(self, i):
if i == len(self.players):
return 0
else:
return i+1
def check_if_I_can_move_on(self):
return False
答案 0 :(得分:9)
我认为应该是
print(l[3:] + l[:3])
答案 1 :(得分:4)
如果您想轮换玩家,请使用deque
来循环播放:
from collections import deque
d = deque([0,1,2,3,4,5,6,7,8])
d.rotate(len(d)//2 + 1)
print(d)
deque([4, 5, 6, 7, 8, 0, 1, 2, 3])
如果你想跟踪每个玩家,你可以继续旋转:
from collections import deque
d = deque([0,1,2,3,4,5,6,7,8])
print(d)
next_p = d[0]
print(next_p)
d.rotate()
print(d)
next_p = d[0]
print(next_p)
输出:
deque([0, 1, 2, 3, 4, 5, 6, 7, 8])
0
deque([8, 0, 1, 2, 3, 4, 5, 6, 7])
8
你可以在get_next_player
函数中移动逻辑,只需让self.players成为deque,这将在所有玩家每次革命开始时使用不同的玩家后自动重启:
def get_next_player(self):
if self.players[0] is None:
self.players.popleft()
self.players.rotate(-1)
self.players.appendleft(None)
else:
n_p = self.players[0]
self.players.rotate()
return n_p
该功能负责旋转,你可以看到下面的逻辑:
# sim round
In [25]: print([get_next_player() for _ in range(10)])
[1, 0, 8, 7, 6, 5, 4, 3, 2, 1]
In [26]: players
# now next player starts
Out[26]: deque([None, 1, 2, 3, 4, 5, 6, 7, 8, 0])
# sim round
In [27]: print([get_next_player() for _ in range(10)])
[2, 1, 0, 8, 7, 6, 5, 4, 3, 2]
In [28]: players
Out[28]: deque([None, 2, 3, 4, 5, 6, 7, 8, 0, 1])
# next player starts
In [29]: print([get_next_player() for _ in range(10)])
[3, 2, 1, 0, 8, 7, 6, 5, 4, 3]
In [30]: players
Out[30]: deque([None, 3, 4, 5, 6, 7, 8, 0, 1, 2])