简体   繁体   English

Python:排序函数的参数

[英]Python: Arguments to sorting function

I am trying to sort a python list of strings. 我正在尝试排序python字符串列表。 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 . 示例:我想根据2个字典中的优先级对字符串列表进行排序。 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. 如果这是不可能的,请你推荐这样做的pythonic方法。

Thanks in advance. 提前致谢。

Try key=priorityDictionary.get 尝试key=priorityDictionary.get

get is a method on a dictionary that takes a key and returns a value, if one is found. get是一个字典上的一个方法,它接受一个键并返回一个值(如果找到一个值)。

Edit: The above solution applies to a case of a single dict . 编辑:上述解决方案适用于单个dict Here is a generalization where values of priorityDict2 are keys for priorityDict1 . 下面是一个泛化其中值priorityDict2是关键priorityDict1

And, as Padriac Cunningham points out, you can use a lambda to sort using nested dicts: 而且,正如Padriac Cunningham指出的那样,你可以使用lambda来使用嵌套的dicts进行排序:

output = sorted(myList, key=lambda element: priorityDict1[priorityDict2[element]])

Use a closure. 使用封闭物。

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

baz = something(len)
print baz('quux')

Code - 代码 -

priorities = {'xyz' : 1, 'cde' : 3, 'abc' : 4, 'pqr' : 2}

arr = ['abc', 'cde', 'pqr', 'xyz', 'cde', 'abc']

arr.sort(key = lambda s : priorities[s])

print(arr)

Output - 输出 -

['xyz', 'pqr', 'cde', 'cde', 'abc', 'abc']

Some slightly more standalone examples: 一些稍微独立的例子:

stringList = ["A1", "B3", "C2", "D4"]
priorityDict = {"A1": 1, "B3": 3, "C2": 2, "D4": 4}

# Reference an accessor function
print sorted(stringList, key=priorityDict.get)

# Provide a lambda function (with "free" closure)
print sorted(stringList, key=lambda x: priorityDict[x])

# Provide a normal function (helper definition needs scope visibility 
# on priority dict, but doesn't have to be global - you can define 
# functions in the scope of other functions a little like lambdas)
def myKey(x):
    return priorityDict[x]

print sorted(stringList, key=myKey)

If you want to pass the value from one dict as the key to the next you need a function or a lambda: 如果要将值从一个dict作为键传递给下一个,则需要一个函数或一个lambda:

l = ["foo", "Foo", "Bar", "bar", "foobar", "Foobar"]

d1 = {"f": 1, "F": 0, "b": 1, "B": 0}
d2 = {1: 10, 0: 20}
print(sorted(l, key=lambda x: d2[d1[x[0]]]))

If a key may not exist you can still use get: 如果某个密钥可能不存在,您仍然可以使用get:

sorted(l, key=lambda x: d2.get(d1.get(x[0], {}), some_default))

Just make sure some_default makes sense and can be compared to the other values. 只需确保some_default有意义,并可与其他值进行比较。

def sortingAlgorithm(primaryDictionary):
  def __cmp__(a, b):
    pass # do something with a, b, and primaryDictionary here
  return __cmp__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM