Han*_*nny 4 python sorting list-comprehension python-3.x
我有一个简单的列表,其中数字是字符串:
simple_list = ['1','2','3','4','5','K','P']
我想首先用alpha对数据进行排序,然后用数字进行排序.
目前我在做:
# Probably a faster way to handle this
alpha_list = [x for x in simple_list if not x.isnumeric()]
grade_list = [x for x in simple_list if x.isnumeric()]
# Put the alpha grades at the beginning of the grade_list
if alpha_list:
grade_list = sorted(alpha_list) + sorted(grade_list)
Run Code Online (Sandbox Code Playgroud)
我确信有一种更快的方法来解决这个问题 - 我似乎无法找到它.
我目前得到的结果是正确的 ['K','P','1','2','3','4','5']
我只是想知道是否有一种方法可以压缩所有那些比多列表理解更有效的方法.
您可以使用返回str.isdigit()测试元组和字符串的键函数对列表进行排序,如果发现字符串为数字,则将其转换为整数:
sorted(simple_list, key=lambda c: (c.isdigit(), int(c) if c.isdigit() else c))
Run Code Online (Sandbox Code Playgroud)
返回:
['K', 'P', '1', '2', '3', '4', '5']
Run Code Online (Sandbox Code Playgroud)