python - python中alpha排序最快的列表

标签 python python-3.x sorting list-comprehension

我有一个简单的列表,其中数字是字符串:

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/

相关文章:

python - 为什么我不能在python中访问这个类成员?

python - 如何在 Python 中的单个测试期间替换类变量?

python : rcvfrom() doesn't work in Linux

python-3.x - pandas 中某列所有元素的乘积

python - 无法从文本文件中打印特定行

c - 错误 sliceShiftLeft() 函数

python - 停止在 python 中打印 'no matches'

python - 按列索引重命名 csv 中的列

php - 按任意顺序对 SQL 行输出进行排序?

ruby - 如何在避免被零除的同时按比率排序?