在这里,我希望我的代码让用户进入游戏然后输入评级,然后循环将其放入字典中但是我想要做的是按照用户输入的评级对字典(游戏)进行排序对于游戏
games = []
def gamef():
print("Here you will type your favorite games and then rate then out of 10 and this will sort them for you. ")
while True:
name = input("Enter your game for the games list: ")
rating = [int(i) for i in input("Enter your rating for the game: ")]
games.append({
"Game Title": name,
"Game Rating": rating
})
cont = input("Want to add another? (Y/N)")
if cont == "N":
break;
if cont == "n":
break;
gamef()
print("Here's your games list: ")
print(games)
games.sort() # <-- Need help here.
print("Here's your list of games in order by rating.")
print(games)
我希望按照评级对字典进行排序,然后打印出来。请帮我把代码排序吧。我应该如何根据其值对字典进行排序,其中许多值将具有重复的非唯一条目?
答案 0 :(得分:0)
没有必要拥有&#34;游戏标题&#34;和#34;游戏评分&#34;作为一系列词典的关键,无论如何,字典本身就是无序的,所以你必须从字典条目中列出一个列表并对其进行排序,但我认为这不会对你的游戏起作用。评级不会是唯一的条目。
为什么不使用pandas数据帧?您可以创建两列数据,然后根据其中一列进行排序
##To Setup the DataFrame
import pandas as pd
Games= pd.DataFrame(columns=["Game Name","Game Rating"])
##To append a row
Appending_Row=pd.Dataframe([[name,rating],columns=["Game Name","Game Rating"])
Games.append(Appending_Row)
然后您可以使用sort_values,如此处所述
答案 1 :(得分:0)
我得到了我的一位朋友的帮助,我知道这有点毫无意义,但这对于学校来说是如此。这是我的代码:
games = {}
def gamef():
print("Here you will type your favorite games and then rate them from 0-9 9 being the highest and this will sort them for you. ")
while True:
name = input("Enter your game for the games list: ")
rating = [int(i) for i in input("Enter your rating for the game: ")]
games.update({name:rating})
cont = input("Want to add another game? (Y/N)")
if cont == "N":
break;
if cont == "n":
break;
gamef()
print("Here's your games list: ")
print(games)
print("Here is your games sorted in order of what you rated them: ")
for w in sorted(games, key=games.get, reverse = True):
print(w, str(games[w]))