Python—使用这两种方法在字典中获取值之间的区别
我是Python的初学者,正在做一个文字游戏。并且有一个Python—使用这两种方法在字典中获取值之间的区别,python,dictionary,enumerate,Python,Dictionary,Enumerate,我是Python的初学者,正在做一个文字游戏。并且有一个{“player1:0”,“player2:0}的字典来记录两个玩家的得分 我有一个重播选项,所以我需要始终将分数存储到该词典中 但当我在每一轮之后使用以下方法检索字典值时: for value, index in enumerate(players): print index, " : ", value 无论打了多少回合,我都能得到: Player 2 : 0 Player 1 : 1 但当我使用: for index i
{“player1:0”,“player2:0}
的字典来记录两个玩家的得分
我有一个重播选项,所以我需要始终将分数存储到该词典中
但当我在每一轮之后使用以下方法检索字典值时:
for value, index in enumerate(players):
print index, " : ", value
无论打了多少回合,我都能得到:
Player 2 : 0
Player 1 : 1
但当我使用:
for index in players:
print index, " : ", players.get(index, 0)
我得到了我想要的实际值
我的问题是,使用这两种方法获取值有什么区别?枚举方法返回索引、值对。对于字典,枚举似乎是枚举密钥集合(这就是为什么会看到密钥)。在这里
for value, index in enumerate(players):
print index, " : ", value
value
是枚举的计数器,这就是为什么总是看到value
从0,1,2,3开始
我想你真正想要的是
for index, value in enumerate(players):
print value, " : ", players[value] # .get works as well
枚举字典通常没有什么意义,因为字典是无序的。
enumerate
正在对字典进行迭代,但默认情况下,您只能:
iter(d)
在字典的键上返回迭代器。这是iterkeys()的快捷方式
你可能想要的是非此即彼
项目()
返回字典的(键、值)对列表的副本
值()
返回字典的值列表的副本。有关dict.items(),请参见注释
我想你想要这个:
for name, score in players.items():
print name, " : ", score
或者可能:
for index, (name, score) in enumerate(players.items()):
print index, " : ", name, " : ", score
为了演示其他两种可能性,此方法将查找所有名称:
for name in players: # or players.keys()
print name
这将查找分数(不带名称):
for score in players.values():
print score