【问题标题】:Alphabetical MergeSort Based on a Last Name [duplicate]基于姓氏的字母合并排序[重复]
【发布时间】:2016-03-02 18:23:02
【问题描述】:

我需要编写一个合并两个文件的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]

列表按以下顺序排列:名字、姓氏、课程、年级。我正在尝试做的是在合并列表后根据姓氏按字母顺序对列表进行排序。我该如何开始呢?

【问题讨论】:

  • 真的需要实现归并排序算法吗?

标签: python sorting python-3.x merge


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    假设您有列表列表:

    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])
    

    【讨论】:

    • operator.itemgetter(1) 会比 lambda 更好
    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      相关资源
      最近更新 更多