python - How to sort a list of tuples such that the key is the sum of the value in the tuples? -


   b= sorted(calls,key=lambda x:x[0]-x[1] ) 

in case subtraction equal list should sorted on basis of 2nd element

sorted(calls, key=lambda x: sum(x))

i don't believe there way specify secondary sort parameter requested, you'll have sort collection twice. sort first value of second element, sort again sum. elements have same sum retain ordering first sort.

edit:

there is way specify multiple sort keys! lambda function can return tuple of values. first item in tuple primary sort key, second item secondary key, , on:

sorted(calls, key=lambda x: (sum(x), x[1]))

thanks @tzot's answer this question !


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -