[英]Sort a list using selection sort
我有一个列表列表,我想要基于列表的第一个元素以升序排序。 如果列表的第一个元素相同,则应根据第二个元素对其进行排序。
到目前为止,我仅能基于列表的前几个元素进行排序。 我已经使用插入排序对它们进行排序。 如果第一个元素相同,如何根据第二个元素对列表进行排序?
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
如果要使用自己的函数进行排序,则可以执行此操作。
要检查第二个元素是否相等,只需编写
(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
列表比较已经可以按照您想要的方式工作(称为词法顺序):比较第一项,如果相等,则比较第二项和后续项。
这意味着您可以用单行对列表进行排序:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.