1

This works perfectly in Python 2.7

def some_compare_func(x, y):
  ....

a = sorted(some_list, lambda x, y: some_compare_func(x, y))

However, the same gives this error in Python 3.x.

TypeError: sorted expected 1 arguments, got 2

Is there a way to sort with a sorting function that works both in Python 2.7 and 3.x?

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • But then it doesn't work with Python 2.7 anymore. Man, this is annoying :( – MetallicPriest Aug 09 '19 at 11:51
  • Yes, tried it, doesn't work in 2.7. Says TypeError: () takes exactly 1 argument (2 given) – MetallicPriest Aug 09 '19 at 11:54
  • 1
    Can you show an actual minimal reproducible example? you also have to specify the key via a keyword argument like `key = lambda`... – Chris_Rands Aug 09 '19 at 11:59
  • https://docs.python.org/3/library/functions.html#sorted – Stop harming Monica Aug 09 '19 at 12:00
  • This how-to article describes a wrapper function that can be used to converted `some_compare_func` to be used in Python 3, although it is designed for porting, not for interoperability https://docs.python.org/3/howto/sorting.html – Deepstop Aug 09 '19 at 12:01
  • the kwarg `cmp=some_compare_function` has been removed in py3. You can use `key`. – Diptangsu Goswami Aug 09 '19 at 12:02
  • Ah- maybe i misunderstood in py3, you need `functools.cmp_to_key` to the old `cmp=` style sorting (it's very rarely useful though) – Chris_Rands Aug 09 '19 at 12:03
  • You may want to have a look at the [official documentation](https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter) that explains how to port code that uses Python 2 sorting to Python 3. – GZ0 Aug 09 '19 at 12:01
  • It's much more efficient to sort using a `key` function, rather than a `cmp` function. The former only gets called once per item in the list, but the latter must be called every time a comparison is performed, so it's significantly slower. – PM 2Ring Aug 09 '19 at 12:36

1 Answers1

5

You can convert the python2 style cmp to key using functools.cmp_to_key()

The following code should work both in python2 and python3

def some_compare_func(x, y):
  ....

import functools
a = sorted(some_list, key=functools.cmp_to_key(some_compare_func))

Check https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter for more details

Sunitha
  • 11,777
  • 2
  • 20
  • 23