【发布时间】:2014-01-16 18:02:12
【问题描述】:
以下代码对对象列表进行排序。
我想要实现的是按其值对“无聊”类型的对象进行排序。我不关心他们在列表中的位置,但最后他们需要排序。我的代码只比较邻居,因此最后仍然是错误的顺序。
需要应用什么类型的排序算法才能正确排序?
class SortMe:
def __init__(self, type, value):
self.type = type
self.value = value
def __repr__(self):
return "<%s %s %s>" % (self.__class__.__name__, self.type, self.value)
stack = (
SortMe('fancy', 15),
SortMe('fancy', 3),
SortMe('boring', 3),
SortMe('boring', 1),
SortMe('fancy', 1),
SortMe('boring', 22),
SortMe('fancy', 22),
SortMe('fancy', 17),
SortMe('boring', 5),
)
def compare(a1, a2):
if a1.type == 'boring' and a2.type == 'boring':
if a1.value > a2.value:
return 1
elif a1.value < a2.value:
return -1
else:
return 0
else:
return 0
stack = sorted(stack, cmp=compare)
print '\n'.join(map(str, stack))
当前输出(顺序错误的无聊对象):
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe boring 1>
<SortMe boring 3>
<SortMe fancy 1>
<SortMe boring 22>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 5>
预期输出(按正确顺序无聊,位置无关紧要):
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe boring 1>
<SortMe boring 3>
<SortMe fancy 1>
<SortMe boring 5>
<SortMe boring 22>
<SortMe fancy 22>
<SortMe fancy 17>
或:
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe fancy 1>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 1>
<SortMe boring 3>
<SortMe boring 5>
<SortMe boring 22>
差不多。
【问题讨论】: