使用自定义比较功能对列表列表进行排序 [英] 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.
我有一个列表清单,其中有5个元素乘以50.我想通过对每个元素应用自定义比较功能来对该列表进行排序.此函数计算元素排序所依据的列表的适用性.我创建了两个函数,比较和适应性:
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))
和
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)
或
sorted(mylist, key=fitness)
或
sorted(mylist, cmp=compare, key=fitness)
或
sorted(mylist, cmp=lambda x,y: compare(x,y))
我也尝试了使用相同参数的list.sort().但是无论如何,函数不会获取列表作为参数,而是获取None
.我不知道为什么,这主要来自C ++,这与我对回调函数的任何想法相矛盾.如何使用自定义功能对该列表进行排序?
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
推荐答案
>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]
上面的作品.你在做不同的事情吗?
The above works. Are you doing something different?
请注意,您的主要功能只是sum
;无需显式编写.
Notice that your key function is just sum
; there's no need to write it explicitly.
这篇关于使用自定义比较功能对列表列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!