在较新的 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/