簡體   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