初始化数据
# random库创建一个5个元素的列表
import random
list01 = [random.randint(1,100) for i in range(5)]
推导过程
# 第一个元素是最大值
for i in range(1, len(list01)):
if list01[0] < list01[i]:
list01[0], list01[i] = list01[i], list01[0]
print(list01)
# [87, 9, 13, 5, 39]
# 第二个元素是最大值
for i in range(2, len(list01)):
if list01[1] < list01[i]:
list01[1], list01[i] = list01[i], list01[1]
print(list01)
# [87, 39, 9, 5, 13]
# 第三个元素是最大值
for i in range(3, len(list01)):
if list01[2] < list01[i]:
list01[2], list01[i] = list01[i], list01[2]
print(list01)
# [87, 39, 13, 5, 9]
最终代码
# 取数据
for r in range(len(list01) - 1):
# 作比较
for c in range(r + 1, len(list01)):
# 找更大
if list01[r] < list01[c]:
# 则交换
list01[r], list01[c] = list01[c], list01[r]
print(list01)
【注解】:
r 的取值范围:[0,1,2,3]
c 的取值范围:[[1,2,3,4],[2,3,4],[3,4],[4]]
取数据:依次取出第1,2,3,4位置上的数
作比较:依次将取出的数据和后面的数据比较
找更大:若后面的数据比当前数据大
交换:就交换(始终保持第一个位置为最大)
如此循环起来,就实现了降序排序。该基础思想很重要。
案例
# 订单列表
list_orders = [
{"cid": 1001, "count": 1},
{"cid": 1002, "count": 3},
{"cid": 1004, "count": 2},
{"cid": 1003, "count": 7},
]
根据购买数量对订单列表降序(大->小)排列,在原列表中体现
for r in range(len(list_orders)-1):# 每次取出一个数据
for c in range(r+1,len(list_orders)): # 与后面的数据比较
if list_orders[r]["count"] < list_orders[c]["count"]: # 比后面的数小
list_orders[r],list_orders[c] = list_orders[c],list_orders[r] # 就交换
print(list_orders)
"""
输出结果:
[
{'cid': 1003, 'count': 7},
{'cid': 1002, 'count': 3},
{'cid': 1004, 'count': 2},
{'cid': 1001, 'count': 1}
]
"""