简体   繁体   中英

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. what is t[0], t[1]?

Working of lambda function in here is like, Sort the list of tuple with the second item. sorted(d.items(), key=lambda t: t[1])

d.items() will be like this.

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

So lambda t:t[1] it return a second elemnt in a given iterator. So it will sort based on the second element. Same as for the lambda t:t[0] it's sort with first element.

Example to understand the lambda function.

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. 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:

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. If you were to choose t[2] you would get IndexError .

First some background: The item() function returns a list of tuples in the dictionary.

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] ). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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