Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

python - Sort a list of lists with a custom compare function

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

def compare(item1, item2):
    if fitness(item1) < fitness(item2):
        return -1
    elif fitness(item1) > fitness(item2):
        return 1
    else:
        return 0

# Calling
list.sort(key=compare)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...