Sort using a custom comparator: Difference between revisions

Line 64:
==[[Python]]==
[[Category:Python]]
'''Interpreter''': 2.4.35
<pre>
def mycmp(s1, s2):
d = len(s2) - len(s1)
if d:
return d if d else cmp(s1, s2)
 
return cmp(s1, s2)
strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
strings.sortprint 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>
Anonymous user