我有一个简单的列表,其中数字是字符串:
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)
我确信有一种更快的方法来处理这个 - 我似乎找不到它。
我目前得到的结果是正确的['K','P','1','2','3','4','5']
我只是想知道是否有一种方法可以将所有内容浓缩下来,这比多个列表理解更有效。
最佳答案
您可以使用返回 str.isdigit()
测试和字符串的元组的键函数对列表进行排序,如果发现字符串是数字,则将其转换为整数:
sorted(simple_list, key=lambda c: (c.isdigit(), int(c) if c.isdigit() else c))
返回:
['K', 'P', '1', '2', '3', '4', '5']
关于python - python中alpha排序最快的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52764472/