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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…