简体   繁体   English

使用Lambda函数进行排序

[英]Using Lambda function in sorted

regular unsorted dictionary 常规未排序字典

>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

dictionary sorted by key 字典按键排序

>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))

dictionary sorted by value 字典按值排序

>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))

How lambda function is working in the above lines. 以上各行中lambda函数的工作方式。 what is t[0], t[1]? t [0],t [1]是什么?

Working of lambda function in here is like, Sort the list of tuple with the second item. lambda函数在这里的工作就像,用第二项对元组列表进行排序。 sorted(d.items(), key=lambda t: t[1]) sorted(d.items(),key = lambda t:t [1])

d.items() will be like this. d.items()将像这样。

[('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)]

So lambda t:t[1] it return a second elemnt in a given iterator. 因此, lambda t:t[1]会在给定的迭代器中返回第二个元素。 So it will sort based on the second element. 因此,它将基于第二个元素进行排序。 Same as for the lambda t:t[0] it's sort with first element. lambda t:t[0] ,只排序第一个元素。

Example to understand the lambda function. 示例了解lambda函数。

In [39]: func = lambda t:t[1]

In [40]: [func(i) for i in d.items()]
Out[40]: [2, 1, 3, 4]

lambda is anonymous function. lambda是匿名函数。 It is convenient to use when specifying sort order, but there is nothing magic about lambda , if you wanted too, you could define the function explicitly: 指定排序顺序时使用起来很方便,但是lambda并没有什么神奇之处,如果您也愿意的话,可以显式定义该函数:

def sorter(x):                                                                                               
    return x[1]                                                                                              

print sorted(d.items(), key=sorter) 

t is the an element in d.items() , so when you choose t[0] you are sorting by first element and when you choose t[1] you are sorting by second element. td.items()的一个元素,因此,当您选择t[0]时,您d.items()第一个元素进行排序;当您选择t[1]时,您d.items()第二个元素进行排序。 If you were to choose t[2] you would get IndexError . 如果选择t[2] ,则会得到IndexError

First some background: The item() function returns a list of tuples in the dictionary. 首先介绍一下背景: item()函数返回字典中的元组列表。

This line: 这行:

>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))

In this line, the sorted function iterates through each item (a tuple), and as per the passed lambda uses the first element of the tuple (the key) to sort ( t[0] ). 在此行中,已排序的函数遍历每个项目(一个元组),并且根据传递的lambda使用该元组的第一个元素(键)进行排序( t[0] )。 The second example follows the same idea, except with the second element of the tuple (the value). 第二个示例遵循相同的想法,除了元组的第二个元素(值)。 As such, each line respectively results in sorting by key and value. 这样,每行分别导致按键和值进行排序。

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

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