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

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

I want to sort the list from the most oriented position on the board to the outermost position.

So, I used positionsList.sort(key=howCentric), and howCentricreturns an integer that represents how centric the position is. the problem is that I would like to Centric function received 2 arguments: a tuple position and length of the card: def howCentric(position, boardSideLength).

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

(I would not want to use a global variable because this is considered a bad habit, and obviously I would not want to create a position tuple that also contains the length of the side of the board, i.e. position = (row, column, boardSideLength))

+4
source share
4 answers

lambda here:

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

The key function passed to the method sortmust take one and only one argument - elements in positionList. However, you can use the factory function, so it howCentriccan access the value boardSideLength:

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

positionsList.sort(key=make_howCentric(boardSideLength))
+1
source

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

Source: https://habr.com/ru/post/1523685/


All Articles