3

我是 python 的初学者,我有一本字典:

players = {"player 1":0, "player 2":0}

在这段代码中,我将描述我想要实现的目标:

def play_ghost():
    for p_id in cycle(players):
        ##code..
        if end_game() : ##if this is true, add 1 to the OTHER player
            ##what to write here ?

抱歉,如果我的问题有点明显,但我真的不想使用if语句等来实现这一点。我正在寻找一个方法或可以选择其他元素的东西(比如在 JavaScript 中我可以选择同级元素)。

4

4 回答 4

2

试试这个:

wins = {"player1": 0, "player2": 0}
this, other = "player1", "player2"
for i in range(rounds_count): # really, variable i don't use
    this, other = other, this # swap players
    if end_game():
        wins[this] +=1
    else:
        wins[other] += 1  
于 2012-10-01T18:47:17.793 回答
1

我认为你真的应该使用有序类型。

players = [0, 0]

players[1] # player 2, because lists are 0-based
players[1:] # all players but the first
# if you want to do more complex selects, do this, but DON'T for simple stuff
[player for index, player in enumerate(players) if index == 1]
于 2012-10-01T18:09:45.373 回答
1

你应该使用lists.
列表类似于dictionaries; 主要区别在于它们按数字而不是键索引。所以:

players = [0, 0]
def play_ghost():
    for index in range(len(players)):
    #code...
        if end_game():
            players[(index + 1) % 2] += 1  # Uses mode to select other player
于 2012-10-01T18:10:16.390 回答
1

咬紧牙关,只定义一个otherdict(这还不错——它使您的其余代码非常易读):

players = {"player 1":0, "player 2":0}
names = players.keys()
other = dict(zip(names, names[::-1]))
# other  = {'player 1': 'player 2', 'player 2': 'player 1'}

def play_ghost():
    for p_id in cycle(players):
        ##code..
        if end_game() : ##if this is true, add 1 to the OTHER player
            players[other[p_id]] += 1
于 2012-10-01T18:14:09.540 回答