a=['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(cmp=lambda x,y:cmp(len(x),len(y)))
print a
为我的无知感到抱歉,我不明白这个lambda函数是如何工作的,我对cmp的了解就是给+1/1/0来显示比较结果,len给出字符串的长度 lambda 函数是如何接受参数的?成对?参加第一、第二然后第三、第四? 那种人在这里做什么? 非常感谢您的帮助!
请您参考如下方法:
为什么不使用键?
a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(key=len)
如果你想使用 cmp 的旧式排序,你必须定义函数 cmp like this :
That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than
所以在你的情况下它可能是这样的:
a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(cmp=lambda x, y: len(x) - len(y))
此函数用于比较基于比较的排序中的两个元素( Timsort ,如果我没记错的话)
