【问题标题】:Sort a list using selection sort使用选择排序对列表进行排序
【发布时间】:2013-01-27 08:56:46
【问题描述】:

我有一个列表列表,我想根据列表的第一个元素按升序对其进行排序。如果列表的第一个元素相同,则应根据第二个元素对其进行排序。

到目前为止,我已经能够仅根据列表的第一个元素进行排序。我使用插入排序对它们进行排序。如果第一个元素相同,如何根据第二个元素对列表进行排序?

def sort_list ():
    # An example of the list to be sorted
    original_list = [['Glenn', 'Stevens'],
                    ['Phil', 'Wayne'],
                    ['Peter', 'Martin'],
                    ['Phil', 'Turville'],
                    ['Chris', 'Turville']]

    sorted_list = list(original_list)

    for index in range(1, len(sorted_list)):           
        pos = index                                 
        while pos > 0 and sorted_list[pos - 1][0] > sorted_list[pos][0]:    
            sorted_list[pos-1], sorted_list[pos] = sorted_list[pos], sorted_list[pos-1]
            pos -= 1                            

    return sorted_list

【问题讨论】:

  • 呃……内置的list.sort 已经做到了。如果您不想破坏original_list,请使用sorted
  • 该函数应该是插入排序的实现,所以我不能使用 list.sort 方法。我还需要原列表不变。
  • sorted_list = list(original_list) 最好写成sorted_list = original_list[:]

标签: python algorithm sorting python-2.7 insertion-sort


【解决方案1】:

如果你想使用自己的函数进行排序,你可以这样做。

要检查第二个元素是否第一个相等,只需编写

   (sorted_list[pos - 1][0] > sorted_list[pos][0] 
or (sorted_list[pos - 1][0] == sorted_list[pos][0] 
    and sorted_list[pos - 1][1] > sorted_list[pos][1]))

而不是

sorted_list[pos - 1][0] > sorted_list[pos][0]

其实你可以写得更短:

sorted_list[pos - 1] > sorted_list[pos]

这正是你所需要的。

python比较列表时,从第一个[0]开始比较它们的元素:

>>> a=[1,2]
>>> b=[1,1]
>>> a<b
False
>>> a=[1,2]
>>> b=[1,3]
>>> a<b
True
>>> a=[1,2]
>>> b=[2,1]
>>> a<b
True

【讨论】:

  • 在一行上似乎写了很多东西。无论如何,谢谢你的代码。
【解决方案2】:

列表比较已经按照您想要的方式进行(称为词法顺序):比较第一个项目,如果它们相等,则比较第二个和后续项目。

这意味着您可以用一行对列表进行排序:

original_list.sort()

如果你必须实现自己的排序,你应该以一种通用的方式实现它,传入一个关键函数(如内置的排序函数)。

def insertion_sort(xs, key=(lambda x: x)):
    result = list(xs)
    for i in xrange(len(result)):
        for pos in xrange(i, 0, -1):
            if key(result[pos-1]) <= key(result[pos]):
                break
            result[pos-1], result[pos] = result[pos], result[pos-1]
    return result

现在您可以按每个子列表的第一个元素进行排序:

print insertion_sort(xs, key=(lambda x: x[0]))

或按词汇顺序:

print insertion_sort(xs)

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2013-04-02
    • 2020-06-18
    • 1970-01-01
    • 2015-06-30
    • 2017-03-19
    • 2022-01-03
    • 2021-06-13
    相关资源
    最近更新 更多