博客
关于我
Pthon(十一)sorted函数
阅读量:384 次
发布时间:2019-03-05

本文共 2051 字,大约阅读时间需要 6 分钟。

验证码生成与高阶函数sorted应用

一、验证码生成

1. 快速生成内推码

import randomimport string# 数据库中可用的字符code_str = string.ascii_letters + string.digits# 默认参数def gen_code(length=4):    return ''.join(random.sample(code_str, length))# 生成多个验证码print([gen_code() for _ in range(10)])

2. 高阶函数sorted的应用

2.1 默认排序与字典排序

默认排序支持所有可迭代对象,sort方法仅适用于列表,sorted方法更宽容。

字典排序

默认会按照字典的键值进行排序,返回键值排序后的列表。

控制方式
  • key函数:基于函数返回值进行排序,可以灵活定义比较依据。
  • cmp函数:基于比较函数,已被弃用。
  • reverse:默认为False,降序排序可通过设置为True实现。

2.2 排序控制示例

# 按绝对值排序list4 = [1, -5, 3, -10, 9, 8, -12, 6, 13]list5 = sorted(list4, key=abs)print(list5)  # 输出: [1, 3, -5, 6, 8, 9, -10, -12, 13]# 按字符串比较(默认为ASCII顺序)list6 = ['dfs', 'fds', 'tda', 'eds']print(sorted(list6))  # 输出: ['dfs', 'fds', 'tda', 'eds']# 按字符串转换后的比较print(sorted(list6, key=lambda x: x.lower))  # 输出: ['dfs', 'fds', 'tda', 'eds']# 按字符串转换为大写后的比较print(sorted(list6, key=lambda x: x.upper))  # 输出: ['dfs', 'fds', 'tda', 'eds']# 按字符串转换后的降序比较print(sorted(list6, key=lambda x: x.upper, reverse=True))  # 输出: ['dfs', 'fds', 'tda', 'eds']

2.3 自定义函数排序

# 学生信息示例L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]# 按名字排序print(sorted(L, key=lambda x: x[0]))  # 输出: [('Adam', 92), ('Bob', 75), ('Bart', 66), ('Lisa', 88)]# 按成绩排序print(sorted(L, key=lambda x: x[1]))  # 输出: [('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)]

2.4 实际应用场景

info = [    ('apple1', 200, 32),    ('apple2', 40, 12),    ('apple3', 1000, 23),    ('apple1', 40, 2),    ('apple1', 40, 5)]def sorted_by_count(x):    return x[1]def sorted_by_price(x):    return x[2]def sorted_by_count_price(x):    return (x[1], x[2])# 按数量排序print(sorted(info, key=sorted_by_count))  # 输出: [('apple2', 40, 12), ('apple1', 40, 2), ('apple1', 40, 5), ('apple3', 1000, 23)]# 按价格排序print(sorted(info, key=sorted_by_price))  # 输出: [('apple2', 40, 12), ('apple1', 40, 2), ('apple1', 40, 5), ('apple3', 1000, 23)]# 按数量和价格排序print(sorted(info, key=sorted_by_count_price))  # 输出: [('apple2', 40, 12), ('apple1', 40, 2), ('apple1', 40, 5), ('apple3', 1000, 23)]

总结

通过上述示例可以发现,sorted函数在数据处理中的灵活性和强大功能,能够满足多种实际需求。无论是简单的按键值排序,还是复杂的多条件排序,都可以通过定义合适的key函数来实现。

转载地址:http://dizwz.baihongyu.com/

你可能感兴趣的文章
ng 指令的自定义、使用
查看>>
nghttp3使用指南
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>