python初级(302) 8 列表(选择排序练习二)
一、复习:
条件循环:while
i = 3 while i > 0: print(i) i –= 1
arr = [2, 3, 5, 7, 9]
while len(arr) > 0:
num = arr[0]
arr.remove(num)
print(arr)
选择排序:
[3, 10, 2, 7, 16]
1、找到最小值get_min()
def get_min(arr): num = arr[0] for i in range(1, len(arr)): if arr[i] < num: num = arr[i] return num get_min([3, 5, 9, 2, 7])
二、选择排序
第二步:将最小值加入到新列表中,并从旧表表中删除
第三步:再次找最小值,直到旧列表为空
def xuanze(arr):
arr2 = list()
while len(arr) > 0:
num = get_min(arr)
arr.remove(num)
arr2.append(num)
return arr2
new_1 = xuanze([3, 5, 9, 2, 7])
print(new_1)
new_2 = xuanze([7, 9, 3, 2, 8])
print(new_2)
new_3 = xuanze([8, 9, 3, 7, 2])
print(new_3)
三、课后扩展
将排序集成到一个类中
class MySort: """ 排序集合 """ def get_min(self, arr): num = arr[0] for i in range(1, len(arr)): if arr[i] < num: num = arr[i] return num def xuanze(self, arr): """ 选择排序 """ arr2 = list() while len(arr) > 0: num = self.get_min(arr) arr.remove(num) arr2.append(num) return arr2 mysort = MySort() arr = mysort.xuanze([3, 5, 2, 7, 8])print(arr)
相关推荐
sunnyhappy0 2020-05-09
哈嘿Blog 2020-10-26
明月清风精进不止 2020-07-05
PythonMaker 2020-07-05
xirongxudlut 2020-06-28
kkpiece 2020-06-16
qscool 2020-06-12
CloudXli 2020-06-11
vs00ASPNET 2020-06-09
Dimples 2020-06-08
kuoying 2020-06-07
JJandYY 2020-05-31
Wyt00 2020-05-30
liuyh 2020-04-03
CloudXli 2020-05-11
世樹 2020-05-11
bizercsdn 2020-05-10