17 选择排序
排序就是按高矮顺序站好队
大纲
选择排序
x = [10,20,30]
for value in x:
print(value)10
20
30x = [10,20,30]
for index,value in enumerate(x):
print(index,value)对嵌套列表的排序
使用内置的排序函数
Last updated
排序就是按高矮顺序站好队
x = [10,20,30]
for value in x:
print(value)10
20
30x = [10,20,30]
for index,value in enumerate(x):
print(index,value)Last updated
0 10
1 20
2 30def find_smallest(x):
smallest = x[0]
smallest_index = 0
for index,value in enumerate(x):
if smallest>value:
smallest = value
smallest_index = index
return smallest,smallest_index
find_smallest([14,6,7,4,9,30])(4, 3)def sort_list(x):
sorted_list = [] # 用于存放排序好的列表
for i in range(len(x)): # 遍历次数是列表的长度
smallest,samllest_index = find_smallest(x) # 找到最小值和编号
sorted_list.append(x.pop(samllest_index)) # 将最小值从X中删除并补充到sorted_list中
return sorted_list
sort_list([14,6,7,4,9,30])[4, 6, 7, 9, 14, 30]def find_smallest(x):
smallest = x[0][1]
smallest_index = 0
for index,value in enumerate(x):
if smallest>value[1]:
smallest = value[1]
smallest_index = index
return smallest,smallest_indexcourse = [['语文',85],['数学',90],['英语',94],['历史',87],['体育',85],['音乐',98]]sort_list(course)[['语文', 85], ['体育', 85], ['历史', 87], ['数学', 90], ['英语', 94], ['音乐', 98]]num_list = [14,6,7,4,9,30]sorted(num_list)[4, 6, 7, 9, 14, 30]sorted(num_list,reverse=True)[30, 14, 9, 7, 6, 4]course = [['语文',85],['数学',90],['英语',94],['历史',87],['体育',85],['音乐',98]]f = lambda x:x[1]
f(course[0])85sorted(course,key=lambda x:x[1])[['语文', 85], ['体育', 85], ['历史', 87], ['数学', 90], ['英语', 94], ['音乐', 98]]