Sort using a custom comparator: Difference between revisions

Content added Content deleted
Line 64: Line 64:
==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]
'''Interpreter''': 2.4.3
'''Interpreter''': 2.5
<pre>
def mycmp(s1, s2):
def mycmp(s1, s2):
d = len(s2) - len(s1)
d = len(s2) - len(s1)
if d:
return d
return d if d else cmp(s1, s2)

return cmp(s1, s2)
strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
print sorted(strings, cmp=mycmp)
strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]

strings.sort(mycmp)
# Alternative with decoration, unfit for very long lists:
print sorted(strings, key=lambda s: (-len(s), s))
</pre>