1

出于这个问题的目的,我已将其缩短,但代码如下所示:

total1=0
total2=0
total3=0
score1=20
score2=30
score3=40


players = [{'user': 'Player1', 'total': total1, 'score': score1},
{'user': 'Player2', 'total': total2, 'score': score2},
{'user': 'Player3', 'total': total3, 'score': score3}]

for i in players:
    if players[i]['score'] <= 30:
        ***code goes here***

我得到这个 TypeError: list indices must be integers, not dict

我怎么说“如果每个玩家得分的值 <= 30”?

如果我只写print players[0]['score']我得到 20。如果我写print players[1]['score']我得到 30,但为什么我不能把它放在一个 for 循环中并让“i”成为数字?

提前致谢!

4

3 回答 3

3

第一个“for”遍历列表“玩家”,因此每个元素都是字典:

for player in players:
    if player['score'] <= 30:
        ...
于 2013-01-30T19:29:05.730 回答
0

当您遍历列表时,每个i都是列表的一个元素,因此请替换players[i]i.

于 2013-01-30T19:28:45.930 回答
0

在这个循环中:

for i in players:
    if players[i]['score'] <= 30:
        ***code goes here***

i是从列表返回的字典,而不是列表中的索引。你想要的是:

for i, player in enumerate(players):
    if player['score'] <= 30:
        ***code goes here***

甚至:

for player in players:
    if player['score'] <= 30:
        ***code goes here***

如果您以后不需要索引

于 2013-01-30T19:29:57.983 回答