如何使用带有多个参数的键函数进行排序?

时间:2014-01-25 11:54:48

标签: python function sorting

我有一个游戏板中的位置列表,即每个位置由元组表示:(行,列)

我希望从列表中最中心的位置到最外面的位置对列表进行排序。

所以我使用positionsList.sort(key=howCentric),而howCentric返回一个整数,表示接收位置的中心位置。 问题是我想howCentric函数接收2个参数:一个位置元组,以及董事会的边长:def howCentric(position, boardSideLength)

关键功能是否可以接收多个参数?

(我不想使用全局变量因为它被认为是一个坏习惯,显然我不想创建一个包含板边长度的位置元组,即position = (row, column, boardSideLength)

4 个答案:

答案 0 :(得分:3)

lambda在这里工作:

positionsList.sort(key=lambda p: howCentric(p, boardLength))

答案 1 :(得分:1)

传递给sort方法的关键函数必须接受一个且只有一个参数 - positionList中的项。但是,您可以使用函数工厂,以便howCentric可以访问boardSideLength

的值
def make_howCentric(boardSideLength):
    def howCentric(position):
        ...
    return howCentric

positionsList.sort(key=make_howCentric(boardSideLength))

答案 2 :(得分:1)

使用functools.partial

from functools import partial

def howCentric(boardSideLength, position):
    #position contains the items passed from positionsList
    #boardSideLength is the fixed argument.
    ...

positionsList.sort(key=partial(howCentric, boardSideLength))

答案 3 :(得分:1)

如果您的Board是一个类,您可以使side_length成为一个实例属性,并在sort函数中使用它:

class Board(object):

    def __init__(self, side_length, ...):
        self.side_length = side_length
        self.positions_list = ...

    def _how_centric(self, pos):
        # use self.side_length and pos

    def position_list_sorted(self):
        return sorted(self.positions_list, key=self._how_centric)
相关问题