简体   繁体   中英

How to print an entire list while not starting by the first item

I'm trying to figure out how to print the following list while not starting by the first item. To be clear: If the list is [0,1,2,3,4,5,6,7,8] , I want to print something like 4,5,6,7,8,0,1,2,3

Here's the code:

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

我认为应该是

print(l[3:] + l[:3])

If you want to rotate the players use a deque to cycle:

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])

If you wanted to keep track of each player you could just keep rotating:

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)

Output:

deque([0, 1, 2, 3, 4, 5, 6, 7, 8])
0
deque([8, 0, 1, 2, 3, 4, 5, 6, 7])
8

You can move the logic inside a get_next_player function, just make self.players a deque, this will automatically restart after all players have had a go starting with a different player each revolution:

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

The function takes care of the rotations, you can see the logic below:

# 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM