基于姓氏的按字母顺序排列的MergeSort

时间:2015-11-28 20:35:20

标签: python sorting python-3.x merge

我需要编写一个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]

列表按顺序排列:firstName,lastName,course,grade。我试图做的是在合并后根据姓氏按字母顺序对列表进行排序。我将如何开始这样做?

3 个答案:

答案 0 :(得分: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函数从列表中提取姓氏并将其用作比较术语

以下是您所需要的一切:

people_ordered = sorted(people, key = lambda x: x[1])

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

告诉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