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
Post a Comment