千锋 2020-01-18
条件循环: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)