簡體   English   中英

按列表中的索引對元組進行排序

[英]sorting tuples by index in lists

因此,我一直在嘗試實現一種排序功能,該功能按列表中元組的索引對元組列表進行排序,我希望該功能執行的工作如下:

def sort(list):
    for item in list:
        list.sort(key=lambda tuple: tuple[1])
    return list

這回來

[('asdasd', 1), ('test', 2), ('34', 3), ('testtt', 5), ('ahj', 12)]

什么時候

listtest = [("test",2),("testtt",5),("ahj",12),("asdasd",1),("34",3)]

叫做。

我之所以不使用它,是因為我來自數學背景,因此我正在嘗試學習如何將算法實現到編程語言中。

我制作的算法如下(示例顯示的列表僅包含元素,而不是元組)

def my_sort(list):
    for i in range(len(list)):
        j = i-1
        key = list[i]
        while (list[j] > key) and (j >= 0):
            list[j+1] = list[j]
            j -= 1
        list[j+1] = key
    return list

確實按索引對元素進行排序。 現在,我要按索引對元組進行排序的部分,到目前為止,我的工作是:

def sort_tuples(list):
    for i in range(len(list)):
        j = i - 1
        key = list[i][1] #returns the index of tuple i
        while (list[j][1] > key) and (j >= 0): #compares the 2nd tuples index with the first tuples index
            list[j+1] = list[j]
            j -= 1 
        key = list[j+1][1] # <----- problem?
    return list

運行時返回

[('test', 2), ('test', 2), ('testtt', 5), ('testtt', 5), ('ahj', 12)]

您必須保留list[i]以便將其重新插入第j個索引:

def sort_tuples(list):
    for i in range(len(list)):
        j = i - 1
        list_i = list[i]
        key = list[i][1] 
        while (list[j][1] > key) and (j >= 0):
            list[j+1] = list[j]
            j -= 1
        list[j+1] = list_i
    return list

print sort_tuples([("test",2),("testtt",5),("ahj",12),("asdasd",1),("34",3)])

Python Zen指出:如果某些代碼易於閱讀和工作,請不要更改它(這是一件好事。這是一件好事。)。

def mysort(myiter):
    result = []
    for i in myiter:
        result[i[1]] = i[0]
    return tuple(result)

是最易讀和優雅的代碼段。

暫無
暫無

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

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