I have a function that evaluates some parameters of the first argument it receives (here item
):
def item_fitness(
item,
fitness_criterion1,
fitness_criterion2
) -> int:
...
return val
It does not matter what it actually does. All that matters is that it takes fitness_criterion1
and fitness_criterion2
in order to check the item
‘s parameters and returns some fitness score.
I would like to use the function as the sorting function in sorted()
like this:
def some_function(items, crit1, crit2):
items = sorted(
items,
key=lambda item, crit1, crit2: item_fitness(
item,
crit1,
crit2
),
reverse=True
)
# Do something with the sorted items
return something
where item
is taken from items
(the actual list of item
instances that is being sorted()
).
How would I do that? The function is also called elsewhere with specific elements from items
.
2
Try this:
def item_fitness(
item,
fitness_criterion1,
fitness_criterion2
) -> int:
# ...
return "val"
def some_function(items, crit1, crit2):
items = sorted(
items,
key=lambda item: item_fitness(
item,
crit1,
crit2
),
reverse=True
)
# Do something with the sorted items
return "something"
print(some_function([1, 2, 3], "crit1", "crit2")) # something
4
Function given to key
may only accept a single argument.
You can use functool.partial
to create a new function with some of the arguments pre-applied.
from functools import partial
def some_function(items, crit1, crit2):
items = sorted(
items,
key=partial(item_fitness, fitness_criterion1 = crit1, fitness_criterion2=crit2),
reverse=True
)
2