1

When I try to port it it errors out asking for key2

Python 2:

def SortItems(self,sorter=cmp):
    items = list(self.itemDataMap.keys())
    items.sort(sorter)
    self.itemIndexMap = items
    self.Refresh()

Python 3:

try:
    cmp
except NameError:
    def cmp(x, y):
        if x < y:
            return -1
        elif x > y:
           return 1
        else:
            return 0

def SortItems(self,sorter=cmp):
    items = list(self.itemDataMap.keys())
    items.sort(key=sorter)
    self.itemIndexMap = items
    self.Refresh()

Getting the error:

items.sort(key=sorter)
TypeError: __ColumnSorter() missing 1 required positional argument: 'key2'

It looks like lambda function needs second argument Any idea how to make it work?

Also tried functools.cmp_to_key:

def SortItems(self):
    import locale
    items = list(self.itemDataMap.keys())
    items= sorted(items, key=cmp_to_key(locale.strcoll)) 
    self.itemIndexMap = items   
    self.Refresh()

Getting error:

    items= sorted(items, key=cmp_to_key(locale.strcoll))
TypeError: strcoll() argument 1 must be str, not int

Probably because I'm sorting integers not strings

How do I make it work for int?

2 Answers 2

1

cmp and key are fundamentally different. However there is a conversion function you can use: functools.cmp_to_key().

Sign up to request clarification or add additional context in comments.

2 Comments

Tried it, gives different error. TypeError: strcoll() argument 1 must be str, not int. I'm sorting integers. Any idea how to use it for integers?
What? Why are you using the strcoll function to compare integers? I don't understand what you are trying to do.
0

From the docs Python3 list.sort():

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments)

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower).

That is, the key callable only takes a single argument in py3. So in this case doing

items.sort(int), or equivalently items.sort(lambda x: x)

will sort a list of int in ascending order.

In general cmp should return the comparison property of the each element of the list.

def cmp(x):
   # code to compute comparison property or value of x
   # eg. return x % 5

Additionally, you can convert the python2 cmp function:

The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.

https://docs.python.org/3/library/stdtypes.html#list.sort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.