首页 > 解决方案 > 对值包含 (str) 数字或字母的列表进行排序

问题描述

如何对包含字符串数字和字母的列表进行排序,以便先按数字排序数字,然后按字母顺序排序?

my_list = ["10","2","1","5","a","b","c"]

disable_sorted_list
"1","2","5","10","a","b","c"

标签: python

解决方案


使用适当的键函数排序:

>>> 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"

推荐阅读