2014-01-25 38 views
4

我有一个游戏板的位置列表,即每个位置都由一个元组表示:(行,列)如何使用具有多个参数的键函数进行排序?

我希望从列表中最中心的位置到最外部位置。

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

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

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

回答

3

lambda s在这里工作:

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

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

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

positionsList.sort(key=make_howCentric(boardSideLength)) 
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)) 
1

如果您Board是一个类,可以使side_length实例属性和使用即在排序功能中:

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) 
相关问题