我希望使用不同的比较函数对字典中的项目进行排序。 请看下面的示例代码。最后一部分使用 cmpRatio 函数与 sorted() 一起使用时出现问题。我不确定自己做错了什么。感谢您提供任何想法!
mydict = { 'a1': (1,6),
'a2': (10,2),
'a3': (5,3),
'a4': (1,2),
'a5': (3,9),
'a6': (9,7) }
# sort by first element of the value tuple: WORKS
print sorted(mydict.iteritems(), key=lambda (k,v): v[0])
# sort by second element of the value tuple: WORKS
print sorted(mydict.iteritems(), key=lambda (k,v): v[1])
# THIS is what I can't get working:
def cmpRatio(x,y):
sx = float(x[0])/x[1]
sy = float(y[0])/y[1]
return sx < sy
# sort by sum of the elements in the value tuple: DOES NOT WORK
print sorted(mydict.iteritems(), key=lambda (k,v): v, cmp=cmpRatio)
{ }
框来格式化您的代码。 - Cameron Sparr