我正在嘗試為我的游戲創建一個高分系統,但只想顯示前 5 名的高分。我用字典來存盤分數和球員的名字。我希望程式在超過 5 個專案時洗掉第一個分數。如何根據順序從字典中洗掉專案?
我試著.pop(index)像這樣使用:
highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
if len(highscores) > 5:
highscores.pop(0)
但是我收到一個錯誤:
Traceback (most recent call last):
File "c:\Users\-----\Documents\Python projects\Python NEA coursework\test.py", line 3, in <module>
highscores.pop(0)
KeyError: 0
有誰知道為什么會這樣?
我找到了一個解決方案:
highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
thislist = []
for keys in highscores.items():
thislist = keys
highscores.pop(thislist[0])
uj5u.com熱心網友回復:
你可以做的是把你的字典變成一個元組(專案)串列,截斷它,然后再變成一個字典。例如,始終只保留插入的最后 5 個值:
highscores = dict(list(highscores.items())[-5:])
(請注意,如果開始時少于 5 個專案,則它是冪等的)。
uj5u.com熱心網友回復:
dict不是有序的。所以首先ordered dict用你想要的順序創建。
你可以試試:
>>> import collections
>>> highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
>>> highscores = collections.OrderedDict(highscores)
>>> highscores.pop(list(new_dict.keys())[0])
'54'
>>> highscores
OrderedDict([('player2', '56'), ('player3', '63'), ('player4', '72'), ('player5', '81'), ('player6', '94')])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390228.html
