博客
关于我
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/

你可能感兴趣的文章
nodejs npm常用命令
查看>>
Nodejs process.nextTick() 使用详解
查看>>
NodeJS yarn 或 npm如何切换淘宝或国外镜像源
查看>>
nodejs 中间件理解
查看>>
nodejs 创建HTTP服务器详解
查看>>
nodejs 发起 GET 请求示例和 POST 请求示例
查看>>
NodeJS 导入导出模块的方法( 代码演示 )
查看>>
nodejs 开发websocket 笔记
查看>>
nodejs 的 Buffer 详解
查看>>
NodeJS 的环境变量: 开发环境vs生产环境
查看>>
nodejs 读取xlsx文件内容
查看>>
nodejs 运行CMD命令
查看>>
Nodejs+Express+Mysql实现简单用户管理增删改查
查看>>
nodejs+nginx获取真实ip
查看>>
nodejs-mime类型
查看>>
NodeJs——(11)控制权转移next
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
nodejs下的express安装
查看>>
nodejs与javascript中的aes加密
查看>>