Python排序最后一个字符

2024-06-26 15:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在较新的Python中,我可以使用sorted函数,并根据字符串的最后几个字符轻松地将其排序:

lots_list=['anything']

print sorted(lots_list, key=returnlastchar)

def returnlastchar(s):     
    return s[10:] 

我如何实现上面的lots_list.sort(),这是在旧版Python(2.3)中使用的?在

“错误:当我尝试使用sorted()the global name sorted is not defined。”在

谢谢!在


Tags: key函数字符串return排序defsort字符
3条回答

不过,根据这篇文章,我手头上没有Python2.3 Sorting a list of lists by item frequency in Python 2.3http://docs.python.org/release/2.3/lib/typesseq-mutable.html 这种方法也适用于您。在

def mycmp(a, b):
    return cmp(a[10:], b[10:])

lots_list.sort(mycmp)

编写自己的排序版本并不难。以下是一个替换项(不包括cmp参数):

def _count():
    i = 0
    while 1:
        yield i
        i += 1

def sorted(iterable, key=None, reverse=False):
    'Drop-in replacement for the sorted() built-in function (excluding cmp())'
    seq = list(iterable)
    if reverse:
        seq.reverse()
    if key is not None:
        seq = zip(map(key, seq), _count(), seq)
    seq.sort()
    if key is not None:
        seq = map(lambda decorated: decorated[2], seq)
    if reverse:
        seq.reverse()
    return seq

Schwartzian transform通常比使用cmp参数更有效(这是较新版本的Python在使用key参数时所做的工作)

lots_list=['anything']

def returnlastchar(s):     
    return s[10:] 

decorated = [(returnlastchar(s), s) for s in lots_list]
decorated.sort()
lots_list = [x[1] for x in decorated]

相关问题 更多 >