Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Arguments to sorting function

Tags:

python

sorting

I am trying to sort a python list of strings. I know that I can use the method sorted and set the attribute key to be a function that implements the behavior I need to sort the elements of the dictionary on. My problem is that this method needs an argument.

UPDATE: I want the method to generalize to multiple arguments.

Example: I want to sort a list of strings based on their priorities in 2 dictionaries . So I need to use those priority dictionaries in sorting the list.

I want something like:

sorted(myList, key=sortingAlgorithm(priorityDictionary1, priorityDictionary2), reverse=True) 

This can be done if I set the priority dictionaries as global variables and then I will not need to have it as an argument to the sorting algorithm. But, I want to be able to do it without global variables.

If this is not possible, can you please recommend the pythonic way of doing this.

Thanks in advance.

like image 457
Hossam Avatar asked Jul 02 '26 09:07

Hossam


2 Answers

Try key=priorityDictionary.get

get is a method on a dictionary that takes a key and returns a value, if one is found.

Edit: The above solution applies to a case of a single dict. Here is a generalization where values of priorityDict2 are keys for priorityDict1.

And, as Padriac Cunningham points out, you can use a lambda to sort using nested dicts:

output = sorted(myList, key=lambda element: priorityDict1[priorityDict2[element]])
like image 178
hilberts_drinking_problem Avatar answered Jul 03 '26 23:07

hilberts_drinking_problem


Use a closure.

def something(foo):
  def somethingsomething(bar):
    return foo(bar)
  return somethingsomething

baz = something(len)
print baz('quux')
like image 24
Ignacio Vazquez-Abrams Avatar answered Jul 03 '26 21:07

Ignacio Vazquez-Abrams