基于最后一个Nam的字母合并排序

2024-09-30 14:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个mergeSort函数来合并两个文件,并根据列表中的一个单词按字母顺序对文件中包含的列表进行排序。 合并后,文件将如下所示:

['Bud', 'Abbott', 51, 92.3]
['Mary', 'Boyd', 52, 91.4]
['Jill', 'Carney', 53, 76.3]
['Jeff', 'Zygna', 50, 82.1]
['Don', 'Adams', 51, 90.4]
['Randy', 'Newman', 50, 41.2]
['Fred', 'Quicksand', 51, 88.8]
['John', 'Ziley', 53, 90.1]

名单按顺序排列:名字,姓氏,课程,年级。我要做的是在合并后根据姓氏按字母顺序对列表进行排序。我该怎么开始呢?在


Tags: 文件函数列表排序顺序字母单词mary
3条回答

告诉sort函数应该使用哪个列表项(key)进行排序。在

from pprint import pprint

merged = [
    ['Bud', 'Abbott', 51, 92.3],
    ['Mary', 'Boyd', 52, 91.4],
    ['Jill', 'Carney', 53, 76.3],
    ['Jeff', 'Zygna', 50, 82.1],
    ['Don', 'Adams', 51, 90.4],
    ['Randy', 'Newman', 50, 41.2],
    ['Fred', 'Quicksand', 51, 88.8],
    ['John', 'Ziley', 53, 90.1]
]

merged.sort(key=lambda x: x[1])
pprint(merged)
>>> [['Bud', 'Abbott', 51, 92.3],
     ['Don', 'Adams', 51, 90.4],
     ['Mary', 'Boyd', 52, 91.4],
     ['Jill', 'Carney', 53, 76.3],
     ['Randy', 'Newman', 50, 41.2],
     ['Fred', 'Quicksand', 51, 88.8],
     ['John', 'Ziley', 53, 90.1],
     ['Jeff', 'Zygna', 50, 82.1]]

请注意,sort()对列表进行了适当的排序,而sorted()则创建了一个新列表。有关详细信息,请参阅文档:Sorting HOW TO。在

其他答案已经指出了如何根据每个元素列表中的特定索引对列表进行排序。但是,如果必须手动合并:

target_list = []
counter1, counter2 = 0, 0
while counter1 < len(list1) or counter2 < len(list2):
    if counter1 == len(list1):
        target_list.extend(list2[counter2:])
        break
    if counter2 == len(list2):
        target_list.extend(list1[counter1:])
        break
    if list1[counter1][1] <= list2[counter2][1]:
# the '<=' seems arbitrary, but ensures sort stability in a recursive sort  
# where list1 is the sorted lower half of a previous split
        target_list.append(list1[counter1])
        counter1 += 1
    else:
        target_list.append(list2[counter2])
        counter2 += 1

假设您有列表:

people = [
    ['Bud', 'Abbott', 51, 92.3],
    ['Mary', 'Boyd', 52, 91.4],
    ['Jill', 'Carney', 53, 76.3],
    ['Jeff', 'Zygna', 50, 82.1],
    ['Don', 'Adams', 51, 90.4],
    ['Randy', 'Newman', 50, 41.2],
    ['Fred', 'Quicksand', 51, 88.8],
    ['John', 'Ziley', 53, 90.1]
]

您可以使用标准的sorted函数按姓氏(即每个列表的第二个元素)对其进行排序,并提供一个key函数从列表中提取姓氏并将其用作比较项。在

以下是您需要的:

^{pr2}$

如果要修改现有列表,也可以使用.sort()方法:

people.sort(key = lambda x: x[1])

相关问题 更多 >