python sort array custom comparator code example
Example 1: python sort array custom comparator
l = [{'prop': 2}, {'prop': 3}, {'prop': 1}]
l.sort(key=lambda x: x['prop'])
Example 2: how to use custom comparator for sorting in python
def compare(item1, item2):
if fitness(item1) < fitness(item2):
return -1
elif fitness(item1) > fitness(item2):
return 1
else:
return 0
# Calling
list.sort(key=compare)