python - 对值包含 (str) 数字或字母的列表进行排序
问题描述
如何对包含字符串数字和字母的列表进行排序,以便先按数字排序数字,然后按字母顺序排序?
my_list = ["10","2","1","5","a","b","c"]
disable_sorted_list
"1","2","5","10","a","b","c"
解决方案
使用适当的键函数排序:
>>> sorted(my_list, key=lambda s: (not s.isdigit(), int(s) if s.isdigit() else s))
['1', '2', '5', '10', 'a', 'b', 'c']
排序键(not s.isdigit(), int(s) if s.isdigit() else s)
是一对(元组)
(bool, str|int)
由于元组是按字典顺序排序的(比较元素,决定第一个不相等的元素),所以数字排在第一位(False < True
)。
我们在排序键中将数字转换为整数,因此它们不会按字母顺序排序
3 < 10 # but
"10" < "3"
推荐阅读
- sql - 在 Altibase DBMS 中测量执行时间
- amazon-web-services - AWS Lambda ListVersionsByFunction 返回的版本是否已排序?
- r - 按 r 中的列值标记 nmds 图
- rabbitmq - 发现在 RabbitMQ 中等待消息的队列
- node.js - 从 Javascript/Node 获取 Skype 状态
- unit-testing - 使用 jest-express,如何对给定请求调用中间件进行单元测试?
- python - Tensorboard 摘要卡在 0
- c# - 使用可视化 C# 写入另一个程序的另存为对话框
- javascript - 如何检查用户是否在控制台中输入了某些内容?Javascript
- mongodb-query - 使用 mongo shell 查找不同长度的字符串字段