在Python中使用自定义比较函数对列表排序列表 [英] Sort list of list with custom compare function in Python

查看:1377
本文介绍了在Python中使用自定义比较函数对列表排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有几个问题,像这样命名,但我似乎无法得到他们的答案。

I know there are several questions named like this, but I can't seems to get their answers to work.

我有一个列表,50次5个元素。现在,我想通过对每个元素应用自定义比较函数对此列表排序。该函数计算元素将被排序的列表的适合度。我创建了两个函数,比较和健身:

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))

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)

sorted(mylist, cmp=compare, key=fitness)

sorted(mylist, cmp=lambda x,y: compare(x,y))

sort()使用相同的参数。但在任何情况下,函数不会得到一个列表作为参数,但。我不知道为什么,从大多数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]]

上述作品。

请注意,您的键功能只是 sum ;没有必要明确写。

Notice that your key function is just sum; there's no need to write it explicitly.

这篇关于在Python中使用自定义比较函数对列表排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆