繁体   English   中英

根据对象属性对对象列表进行排序

[英]Sort a list of objects based on an object property

在这里,我希望我的代码让用户输入游戏然后输入评级,然后循环将其放入字典中,但我想按照用户为游戏输入的评级对字典(游戏)进行排序

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)

我希望这个按评级对字典进行排序,然后打印出来。 请帮我对代码进行排序。 我应该如何根据字典的值对字典进行排序,其中许多值将具有重复的、非唯一的条目?

没有必要将“游戏名称”和“游戏评级”作为一系列词典的关键,无论如何,词典本质上是无序的,因此您必须从词典条目中列出并对其进行排序,但我不要认为这会奏效,因为您的游戏评分不会是唯一条目。

为什么不使用熊猫数据框? 您可以制作两列数据,然后根据其中一列进行排序

##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 ,如回答here

如何从一列对熊猫数据框进行排序

我从我的一位朋友那里得到了帮助,我知道这有点毫无意义,但这是为了学校。 这是我的代码:

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]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM