Pok*_*rof 6 python sorting string python-2.3
在较新的Python中,我可以使用sorted函数,并根据它们的最后几个字符轻松地排序字符串列表:
lots_list=['anything']
print sorted(lots_list, key=returnlastchar)
def returnlastchar(s):
return s[10:]
Run Code Online (Sandbox Code Playgroud)
如何实现上述lots_list.sort()Python(2.3)中使用的上述内容?
"错误:当我尝试使用时sorted(),the global name sorted is not defined."
谢谢!
在使用Schwartzian变换通常比使用更高效的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]
Run Code Online (Sandbox Code Playgroud)
我手边没有python 2.3,但根据这篇文章 在Python 2.3中按项目频率排序列表列表 http://docs.python.org/release/2.3/lib/typesseq-mutable.html 这个方法也应该适合你.
def mycmp(a, b):
return cmp(a[10:], b[10:])
lots_list.sort(mycmp)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4672 次 |
| 最近记录: |