代码之家  ›  专栏  ›  技术社区  ›  Hanny

python中alpha排序最快的列表

  •  4
  • Hanny  · 技术社区  · 6 年前

    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']

    1 回复  |  直到 6 年前
        1
  •  6
  •   blhsing    6 年前

    可以使用返回 str.isdigit() 测试和字符串,如果发现字符串是数字,则将其转换为整数:

    sorted(simple_list, key=lambda c: (c.isdigit(), int(c) if c.isdigit() else c))
    

    ['K', 'P', '1', '2', '3', '4', '5']