Python按三个标准排序

时间:2017-10-17 22:16:34

标签: python list sorting

我正试图按照几个标准(长度,后缀和按顺序按字母顺序排序)处理排序。虽然我无法控制它,而我似乎能做的就是按照长度排序......

这是我的代码(python 2.7.9):

#!/usr/bin/python

sortme = [
    'one.ab',
    'two.ef',
    'three.ab',
    'six.ef',
    'seven.jk',
    'eight.ef',
    'nine.xy',
    'five.xy',
    'ten.ab',
    'Four.ef'
]

sortme.sort(key=lambda item: (-len(item), item), reverse=True)

print(sortme)

这得到长度部分,但我真的想要得到:

(ab)
one.ab
ten.ab
three.ab

(ef)
six.ef
two.ef
four.ef
eight.ef

(jk)
seven.jk

(xy)
five.xy
nine.xy

3 个答案:

答案 0 :(得分:1)

您可以将多个排序键指定为元组:

sortme.sort(key=lambda item: (item.split('.')[1], len(item), item), reverse=False)

print("\n".join(sortme))

输出:

one.ab
ten.ab
three.ab
six.ef
two.ef
Four.ef
eight.ef
seven.jk
five.xy
nine.xy

答案 1 :(得分:0)

sortme.sort(key=lambda item: (-len(item),item.rsplit(".",1)[-1], item), reverse=True)

您只需添加第3条标准......我真的建议您与导师或老师坐下来。

你可以随时将其分解为自己的功能,使其更容易理解

def sort_key(item):
    return -len(item),item.rsplit(".",1)[-1],item

sortme.sort(key=sort_key,reverse=True)

答案 2 :(得分:0)

您还可以尝试cmp功能:

import re


sortme = [
    'one.ab',
    'two.ef',
    'three.ab',
    'six.ef',
    'seven.jk',
    'eight.ef',
    'nine.xy',
    'five.xy',
    'ten.ab',
    'Four.ef'
]

def _cmp(first, second):
    first_type = first.split('.')[-1]
    second_type = second.split('.')[-1]
    if first_type == second_type:
        return cmp(len(first), len(second))

    return cmp(first_type, second_type)

sortme.sort(cmp=_cmp)

print(sortme)