Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, sort list with two arguments in compare function

Tags:

python

list

I was looking a lot and reading a lot of question, but I cannot figure out how to give two arguments to the key of sort method, so I can make a more complex comparison.

Example:

class FruitBox():
  def __init__(self, weigth, fruit_val):
    self.weigth = weigth
    self.fruit_val = fruit_val

I want to compare the FruitBox by fruit_val, but! Also they box heavier are bigger than others.

So it would be:

f1 = FruitBox(2,5)
f2 = FruitBox(1,5)
f3 = FruitBox(2,4)
f4 = FruitBox(3,4)

boxes = [f1,f2,f3,f4]
boxes.sort(key = ???) # here is the question

Expected result: => [FruitBox(2,4),FruitBox(3,4),FruitBox(1,5),FruitBox(2,5)]

Is there a way to send a function with 2 arguments, when I do it something like

def sorted_by(a,b):
  #logic here, I don't know what will be yet

and I do

boxes.sort(key=sorted_by)

It throws:

Traceback (most recent call last):
  File "python", line 15, in <module>
TypeError: sort_by_b() missing 1 required positional argument: 'b'

How can I give Two Arguments to the key of sort?

like image 284
A Monad is a Monoid Avatar asked Apr 13 '26 00:04

A Monad is a Monoid


1 Answers

This answer is dedicated to answering:

How can I give Two Arguments to the key of sort?


The old style compare way to sort is gone in Python 3, as in Python 2 you would do:

def sorted_by(a,b):
    # logic here
    pass

boxes.sort(cmp=sorted_by)

But if you must use it Python 3, it’s still there, but in a module, functools, it’s purpose is to convert the cmp to key:

import functools 
cmp = functools.cmp_to_key(sorted_by)
boxes.sort(key=cmp)

The preferred way to sort is to make a key function that returns a weight for the sorting to base on. See Francisco’s answer.

like image 51
Taku Avatar answered Apr 15 '26 12:04

Taku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!