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

弾丸を噛んで、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 に答える
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 に答える