Python习题之列表排序,4种方法

 1 def sort_list_method_1(a):
 2     return sorted(a)
 3 
 4 
 5 print(sort_list_method_1([1, 4, 2]))
 6 
 7 
 8 def sort_list_method_2(a):
 9     for i in range(len(a)):
10         m = i
11         for z in range(i+1, len(a)):
12             if a[m] > a[z]:
13                 m = z
14         a[m], a[i] = a[i], a[m]
15     return a
16 
17 
18 print(sort_list_method_2([2, 4, 1]))
19 
20 
21 def sort_list_method_3(a):
22     b = []
23     for i in range(len(a)):
24         b.append(min(a))
25         a.remove(min(a))
26     return b
27 
28 
29 print(sort_list_method_3([4, 2, -2, 8]))
30 
31 
32 def sort_list_method_4(a):
33         return a.sort()
34 
35 
36 b = [4, 3, 7, -2, 1]
37 sort_list_method_4(b)
38 print(b)
View Code

将之前写过的列表的排序,写成函数,实现传入一个列表能够进行排序的功能。 # (不用原地排序,新创建列表排序即可。)

猜你喜欢

转载自www.cnblogs.com/tttzqf/p/9270509.html