drizzit
drizzit

Reputation: 43

How to sort using key function which takes more than one argument?

I have a list of positions in a game board, i.e., each position is represented by a tuple: (row, column)

I wish to sort the list from the most centric position in the board, to the most outer position.

So I used positionsList.sort(key=howCentric), while howCentric returns an integer which represents how centric the received position is. the problem is that I would like howCentric function to receive 2 arguments: a position tuple, and the board's side length: def howCentric(position, boardSideLength).

Is it possible for the key function to receive more than one argument?

(I wouldn't like to use a global variable because it is considered a bad habit, and obviously I wouldn't like to create a position tuple which contains also the board's side length, i.e., position = (row, column, boardSideLength))

Upvotes: 4

Views: 1002

Answers (4)

Eric
Eric

Reputation: 97571

lambdas work here:

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

Upvotes: 3

jonrsharpe
jonrsharpe

Reputation: 122007

If your Board is a class, you can make side_length an instance attribute and use that in the sort function:

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)

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

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

Upvotes: 1

unutbu
unutbu

Reputation: 879381

The key function passed to the sort method must accept one and only one argument -- the items in positionList. However, you could use a function factory so howCentric can access the value of boardSideLength:

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

positionsList.sort(key=make_howCentric(boardSideLength))

Upvotes: 1

Related Questions