python - 在 Python 2.3 中按最后 N 个字符对字符串列表进行排序

标签 python string sorting python-2.3

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

lots_list = ['anything']

print sorted(lots_list, key=returnlastchar)

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

如何在较旧的 Python (2.3) 中将上述内容实现到 lots_list.sort()

“错误:当我尝试使用 sorted() 时,未定义已排序的全局名称。”

最佳答案

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

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]

关于python - 在 Python 2.3 中按最后 N 个字符对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11304005/

相关文章:

python - Django sendmail SSL 错误 EOF 发生违反协议(protocol)

java - 我需要让扫描仪检查输入是否为 "quit",如果不是,则接受一个整数

java - Java中将一个字符串拆分为多个字符串

python-2.7 - 排序字典列表值

r - 按R中的多列排序矩阵

Python 多个用户同时追加到同一个文件

python - 是否可以更改|更新我的 "Temporary IPv6 Address"- windows(最好通过 Python)

python 处理 DictReader 缺少键

c - 如何使用位操作将 char 数组 [example 42] 转换为 int equivilant [int 42]?

java - 根据对象中的变量对对象数组列表进行排序