TypeError; Must use keyword argument or key function in python 3.x

I am new to python trying to port the script in 2.x to 3.x. I encounter a TypeError error; Must use keyword argument or key function in python 3.x. Below is a code snippet: Please help

def resort_working_array( self, chosen_values_arr, num ):
    for item in self.__working_arr[num]:
        data_node = self.__pairs.get_node_info( item )

        new_combs = []
        for i in range(0, self.__n):
            # numbers of new combinations to be created if this item is appended to array
            new_combs.append( set([pairs_storage.key(z) for z in xuniqueCombinations( chosen_values_arr+[item], i+1)]) - self.__pairs.get_combs()[i] )
        # weighting the node
        item.weights =  [ -len(new_combs[-1]) ]    # node that creates most of new pairs is the best
        item.weights += [ len(data_node.out) ] # less used outbound connections most likely to produce more new pairs while search continues
        item.weights += [ len(x) for x in reversed(new_combs[:-1])]
        item.weights += [ -data_node.counter ]  # less used node is better
        item.weights += [ -len(data_node.in_) ] # otherwise we will prefer node with most of free inbound connections; somehow it works out better ;)

    self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) )
+6
source share
3 answers

Looks like the problem is on this line.

self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) )

The caller keymust take only one argument. Try:

self.__working_arr[num].sort(key = lambda a: a.weights)
+14
source

Exactly the same error message appears if you try to pass a key parameter as a positional parameter.

Wrong:

sort(lst, myKeyFunction)

Correct:

sort(lst, key=myKeyFunction)

Python 3.6.6

+1
source

@Kevin, - / @featuresky:

functools.cmp_to_key cmp ( ), , 2 -. ; :

self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) )

:

from functools import cmp_to_key

[...]

def cmp(x, y): return (x > y) - (x < y)
self.__working_arr[num].sort(key=cmp_to_key(lambda a,b: cmp(a.weights, b.weights)))

, python python2. , , , , "" .

OTOH python2 ( python3), /, "" .

Besides the fact that it works, I certainly would not recommend the widespread use of this hack! But I thought it was worth sharing.

0
source

All Articles