Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—选择字典中的其他元素_Python_Dictionary_Iterator - Fatal编程技术网

Python—选择字典中的其他元素

Python—选择字典中的其他元素,python,dictionary,iterator,Python,Dictionary,Iterator,我是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

我是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中,我可以选择同级元素)。

我认为您应该使用有序类型

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]

您应该使用
列表

列表类似于
词典
;主要区别在于它们是按数字而不是按键进行索引的。 因此:

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

咬紧牙关,只需定义一个
other
dict(没那么糟糕——它使代码的其余部分非常可读):

试试这个:

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  

我在你的代码中没有看到对其他玩家的引用。也许我不明白什么,但是为什么不使用
播放器[另一个播放器id]+=1
?对于范围内的索引(播放器)来说
不起作用(
范围
需要整数参数)。这里缺少了一个
len
(以及行末尾的一个冒号
)。我不会说列表“与字典不同,只是…”。它们在某些方面相似,但数据结构仍然非常不同。例如,它们没有排序。
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