I know there are several questions named like this, but I can't seems to get their answers to work.
I have a list of lists, 50 times 5 elements. Now I want to sort this list by applying a custom compare function to each element. This function calculates the fitness of the list by which the elements shall be sorted. I created two functions, compare and fitness:
def compare(item1, item2):
return (fitness(item1) < fitness(item2))
and
def fitness(item):
return item[0]+item[1]+item[2]+item[3]+item[4]
Then I tried to call them by:
sorted(mylist, cmp=compare)
or
sorted(mylist, key=fitness)
or
sorted(mylist, cmp=compare, key=fitness)
or
sorted(mylist, cmp=lambda x,y: compare(x,y))
Also I tried list.sort() with the same parameters. But in any case the functions don't get a list as an argument but a None
. I have no idea why that is, coming from mostly C++ this contradicts any idea of a callback function for me. How can I sort this lists with a custom function?
Edit I found my mistake. In the chain that creates the original list one function didn't return anything but the return value was used. Sorry for the bother
Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:
The above works. Are you doing something different?
Notice that your key function is just
sum
; there's no need to write it explicitly.You need to slightly modify your
compare
function and usefunctools.cmp_to_key
to pass it tosorted
. Example code:Output:
Works :)