繁体   English   中英

如果有一个整数与字符串绑定最小数字,我如何对列表进行排序?

[英]How do I sort a list if there is an integer tied to a string by the smallest number?

我对编程很陌生,我正在尝试在python 3中为数字猜谜游戏制作一个排行榜,在那里你有得分,然后名字按照最低得分排序:

leaderboard_list = [0,0,0,0,0]
while True:
    leaderboard_list.sort()
    print("This in the leaderboard",leaderboard_list)
    name = ("What is your name?")
    while user_num != answer:
        user_num = input("Guess a number: ")
        if user_num = answer:
            print("YAY")
        else:
            score = score + 1
   leaderboard_list.append(score+" "+name)

我已经尝试了很多不同的方法并且已经发现,如果你得到11分,那么它会说你在领导板上的得分高于得分为2的人,这不应该。 我还尝试将分数更改为int类型,但是在同一列表中不能有int和字符串。 我怎么能绕过这个?

排行榜本身应存储更多结构化数据; 仅使用字符串来显示数据。

# Store a list of (name, score) tuples
leaderboard = []
while True:

    # Print the leaderboard
    print("This in the leaderboard")
    for name, score in leaderboard:
        print("{} {}".format(score, name))

    name = ("What is your name?")
    score = 0
    while user_num != answer:
        user_num = input("Guess a number: ")
        if user_num == answer:
            print("YAY")
        else:
            score = score + 1

   # Store a new score
   leaderboard.append((name, score))
   # Sort it
   leaderboard = sorted(leaderboard, key=lambda x: x[1], reverse=True)
   # Optional: discard all but the top 5 scores
   leaderboard = leaderboard[:5]

请注意,维护排序列表的方法比在最后添加新分数后使用整个排行榜更好,但这超出了此答案的范围。

字典解决方案

字典非常适​​合存储分数并将它们链接到用户名的任务。 字典无法直接排序。 但是,在这篇文章中有一个简单的解决方案。

而且,在OP中,名称声明是错误的,因为它没有从用户获得任何值。 使用以下代码,它完美地工作。 还应添加结束while循环的条件。

import operator

#Store the names and scores in a dictionary
leaderboard_dict = {}
#Random number
answer = 3
while True:
    #Sort the dictionary elements by value
    sorted_x = sorted(leaderboard_dict.items(), key=operator.itemgetter(1))
    #Rewrite the leaderboard_dict
    leaderboard_dict = dict(sorted_x)
    print("This in the leaderboard",leaderboard_dict)
    name = input("What is your name?")
    #initialize score and user_num for avois crashes
    user_num = -1
    score = 0
    while user_num != answer:
        user_num = input("Guess a number: ")
        if user_num is answer:
            print("YAY")
        else:
            score += 1
    leaderboard_dict[name] = score

NumPy阵列解决方案

编辑:如果你想为每个玩家存储多个分数,我会使用NumPy数组 ,因为它们可以让你做大量的操作,比如通过切片和获取数字顺序来排序索引,这就是OP的请求。 此外,他们的语法是非常容易理解的和Pythonic:

import numpy as np
#Random number
answer = 3
ranking = np.array([])

while True:
    name = input("What is your name?")
    user_num = -1
    score = 1
    while user_num != answer:
        user_num = input("Guess a number: ")
        if user_num is answer:
            print("YAY")
        else:
            score += 1
    #The first iteration the array is created
    if not len(ranking):
        ranking = np.array([name, score])
    else:
        ranking = np.vstack((ranking, [name,score]))
        #Get the index order of the scores
        order = np.argsort(ranking[:,1])
        #Apply the obtained order to the ranking array
        ranking = ranking[order]

以及它的一个使用示例:

>> run game.py
What is your name?'Sandra'
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sarah'
Guess a number: 1
Guess a number: 5
Guess a number: 78
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sandra'
Guess a number: 2
Guess a number: 4
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 1
Guess a number: 3
YAY

作为输出:

print ranking
[['Sandra' '1']
['Paul' '2']
['Paul' '2']
['Sandra' '3']
['Sarah' '5']]  

暂无
暂无

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

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