简体   繁体   English

pygame排序列表对象是字符串

[英]pygame sorting list objects that are strings

I am making a game were at the start you enter your name and then it is saved as a variable. 我正在制作一个游戏,一开始您要输入名称,然后将其另存为变量。 Then, you perform specific tasks and your time is counted in seconds. 然后,您执行特定任务,并且时间以秒为单位。 At the end, I want to remove the worst time, the Scoreboard to save your time if you beat a record, sort that list that contains the Scoreboard and then save it. 最后,我想删除最糟糕的时间,即记分牌,以便在您打破记录时节省时间,对包含记分牌的列表进行排序,然后保存。 This is my try at that, but it can't sort it in decending order since the objects in the lists are strings in order to contain the names of the players: 这是我的尝试,但是由于列表中的对象是字符串以包含播放器的名称,因此无法按降序对其进行排序:

        end = time.time()
        print(end - start)
        b = int(end - start)
        if b < int(Scoreboard[4]):
            message_display("NEW RECORD!", 2, 2)
            del Scoreboard[-1]
            Scoreboard.append(name+ str(b))
            Scoreboard.sort(reversed=True)

EDIT: Just to be clear, Scoreboard is a list and it's contents are from a json file 编辑:只是要清楚,记分板是一个列表,它的内容来自json文件

I would say you could make each element in the scoreboard list into a nested tuple in the list- I don't know what file type you're using, but I expect you could save it in this format. 我想说您可以将记分板列表中的每个元素放入列表中的嵌套元组-我不知道您使用的是哪种文件类型,但是我希望您可以将其保存为这种格式。 If it was a list of nested tuples, you could sort it using the [sorted] method. 如果它是嵌套元组的列表,则可以使用[sorted]方法对其进行排序。 The [key] parameter will allow you to sort based on the index position 1 instead of 0, and the [reverse] parameter will allow it to sort in descending order. [key]参数将允许您根据索引位置1而不是0进行排序,[reverse]参数将允许其以降序排序。

data = sorted(data, reverse=True, key=lambda x:x[1])

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

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