Python 自定义算法1 —— 找最值【逆序】

初始化数据

# 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}
]
"""
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值