我想知道如何实现高级排序函数,我可以将它作为元组元素传递给python'sorted'函数的key参数。
以下是一个描述我想要做的事情的例子:
class Book:
def __init__(self, name, author, language, cost):
self.name = name
self.author = author
self.language=language
self.cost = cost
bookList = [list of books]
firstLanguage = "Armenian"
possibleLanguages = ["English", "Spanish", "Armenian", "French", "Chinese", "Swahili"]
possibleLanguages.remove("Armenian")
sortedBookList = sorted(bookList, key=(sortByName,
sortByFirstLanguage(firstLanguage), sortByLanguages(possibleLanguages) ))
基本上我想实现上面描述的'sortByFirstLanguage'和'sortByLanguages'函数,以便我可以将它们作为'key'参数的元组项传递给python'sorted'函数。下面是一些关于自定义排序函数应该是什么样子的示例代码:
def sortByName(elem):
return elem.name
def sortByFirstLanguage(elem, firstLanguage):
if elem.language == firstLanguage:
return 1
else:
return -1
def sortByLanguages(elem, possibleLanguages):
if elem.language in possibleLanguages:
return possibleLanguages.index(elem.language)
我怎么能告诉'key'参数传递额外的参数'firstLanguage'&& 'possibleLanguages'到我上面显示的自定义排序功能?
答案 0 :(得分:5)
Ashish在评论中指出,我们首先需要结合这些功能,因为key
只接受一个函数。如果我们返回函数结果的序列(列表,元组),Python将做正确的事情,只比较后面的(更右边)元素,如果前面的元素相等(source)。
我知道有几种方法可以做到这一点。
使用lambdas:
sortedBookList = sorted(
bookList,
key=lambda elem: (sortByName(elem),
sortByFirstLanguage(elem, firstLanguage),
sortByLanguages(elem, possibleLanguages)))
使用高阶函数:
def key_combiner(*keyfuncs):
def helper(elem):
return [keyfunc(elem) for keyfunc in keyfuncs]
return helper
def sortByFirstLanguage(firstLanguage):
def helper(elem):
return elem.language == firstLanguage # True > False
return helper
def sortByLanguages(possibleLanguages):
def helper(elem):
if elem.language in possibleLanguages:
return possibleLanguages.index(elem.language)
return helper
sortedBookList = sorted(bookList,
key=key_combiner(sortByName,
sortByFirstLanguage(firstLanguage),
sortByLanguages(possibleLanguages))
Lambdas对我来说似乎最干净,所以这可能是我使用的。