Python - 如何在字典列表的FOR循环中的IF语句中比较键的值?
为了方便这个问题,我把代码简化了,但大致是这样的:
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,但为什么我不能把它放在一个循环里,让“i”变成数字呢?
提前谢谢你们!
3 个回答
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***
如果你后面不需要索引的话
0
当你遍历这个列表时,每个 i
都是列表中的一个元素,所以把 players[i]
替换成 i
就可以了。
3
第一个“for”循环会遍历列表'players',所以每次循环中的元素都是一个字典:
for player in players:
if player['score'] <= 30:
...