【发布时间】: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