簡體   English   中英

嘗試在python中排序2d數組以輸出高分列表

[英]Trying to sort 2d array in python to output a list of highscores

因此,我正在制作一個游戲服務器,允許用戶登錄並選擇要玩的游戲,然后將他們獲得的任何分數添加到記事本文件中,格式為:(即二十一點)用戶名,#chips,“ chips”。 現在,我想對文件中的所有分數進行排序以顯示在gui上,但是我不允許使用諸如sorted之類的內置函數,而必須提出一種算法。 我嘗試了冒泡排序和插入排序,但沒有任何運氣。 這是我到目前為止的內容:

blackjackList = [['harsh', '4', 'chips'], ['ahmed', '25', 'chips'], ['yousef', '1003', 'chips'], ['krushangi', '200', 'chips'], ['bombberman', '1202', 'chips']]
def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i][1]>alist[i+1][1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp
        return alist

當前輸出

[['ahmed', '25', 'chips'], ['yousef', '1003', 'chips'], ['krushangi', '200', 'chips'], ['bombberman', '1202', 'chips'], ['harsh', '4', 'chips']]

當我將其與21點列表一起使用時,我希望它使21點列表按升序從降序排列。

您的問題是return語句縮進過多,並且位於for循環內,因此它僅在返回之前進行一次遍歷。

另外,您正在將數字作為字符串進行比較。 這不會給出預期的順序(例如“ 10”小於“ 2”)。 您應該使用int()將其轉換為整數,然后將其正確排序。

您可以使用quicksort對數組進行排序。

>>> blackjackList = [['harsh', '4', 'chips'], ['ahmed', '25', 'chips'], ['yousef', '1003', 'chips'], ['krushangi', '200', 'chips'], ['bombberman', '1202', 'chips']]
>>> def quicksort(arr):
...     if len(arr)==0: return []
...     if len(arr)==1: return arr
...     left = [i for i in arr[1:] if int(i[1])<int(arr[0][1])]    # for descending, exchange
...     right = [i for i in arr[1:] if int(i[1])>=int(arr[0][1])]  # these two values
...     return quicksort(left)+[arr[0]]+quicksort(right)
...
>>> quicksort(blackjackList)
[['harsh', '4', 'chips'], ['ahmed', '25', 'chips'], ['krushangi', '200', 'chips'], ['yousef', '1003', 'chips'], ['bombberman', '1202', 'chips']]

上面的代碼給出了升序的排序列表。 要獲得降序排序列表,只需在代碼中交換leftright的值即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM