I know there are several questions named like this, but they don't seem to work for me.
I have a list of lists, 50 times 5 elements. 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
compare
function is incorrect, since it only returns True or False, and doesn't distinguish betweenitem1
anditem2
being equal anditem1
being greater thanitem2
. The correct way to writecompare
would be to returncmp(fitness(item1), fitness(item2))
. But usingkey
is better.cmp
keyword was removed in Python 3. You can now usekey=functools.cmp_to_key(<function>)
after importingfunctools
.