Skip to content

Instantly share code, notes, and snippets.

@dsoike
Created March 20, 2019 20:01
Show Gist options
  • Save dsoike/c336cc7b6008c40bbd0ea354c606ce76 to your computer and use it in GitHub Desktop.
Save dsoike/c336cc7b6008c40bbd0ea354c606ce76 to your computer and use it in GitHub Desktop.
Custom Sort Function in Python
# sort things by highest priority & lowest time
thing1 = {'id': 1, 'priority': 1, 'time': 500}
thing2 = {'id': 2, 'priority': 5, 'time': 400}
thing3 = {'id': 3, 'priority': 5, 'time': 600}
thing4 = {'id': 4, 'priority': 10, 'time': 100}
things = [thing1, thing2, thing3, thing4]
def sort_things(thing1, thing2):
if thing1['priority'] > thing2['priority']:
return -1
elif thing1['priority'] < thing2['priority']:
return 1
elif thing1['time'] < thing2['time']:
return -1
elif thing1['time'] > thing2['time']:
return 1
else:
return 0
things_sorted = sorted(things, cmp=sort_things)
things_sorted_ids = map(lambda x: x['id'], things_sorted)
expected_sorted_ids = [4, 2, 3, 1]
print('sorted_ids={}'.format(things_sorted_ids))
print('expected_ids={}'.format(expected_sorted_ids))
assert(things_sorted_ids == expected_sorted_ids)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment