Usage of key parameter of sort() function in python

Today, while learning the anonymous function lambda, I encountered a problem that I didn't really understand.

strings = ['foo', 'card', 'bar', 'aaaa', 'abab']
# 根据字符串中不同字母的数量对一个字符串集合进行排序
strings.sort(key=lambda x: len(set(list(x))))

The output of the above strings is: ['aaaa','foo','abab','bar','card'] The
result is clear, but the process was not clear at the beginning.
Later, Baidu took a look and found out after referring to other people's analysis.
The main purpose is to understand the meaning of the parameter key in the sort() function: what is
passed to the key parameter is a function, which specifies each element in the iterable object to sort according to the function.
For example:

# 这里先看一个不带key参数的sort()函数,大家很容易知道结果
li = [[1, 7], [1, 5], [2, 4], [1, 1]]
li.sort()
print(li)  
# [[1, 1], [1, 5], [1, 7], [2, 4]] 默认按照0维排序 再按照1维排序

def fun(li):
	return li[1]
# 这时将函数fun传递给参数key 得出结果
li.sort(key=fun)
print(li) # [[1, 1], [2, 4], [1, 5], [1, 7]]

We can find that it seems that the second number of each child element in li is sorted.
This is the function of the key parameter. The sort() function passed in the key parameter is executed for each sub-element [1,7],[1,5],[2,4],[1,1] in li The fun() function returns their first number, which is 7, 5, 4, and 1. And then sort to get 1,4,5,7. Use the result to sort the original li and finally get [[1,1],[2,4],[1,5],[1,7]].
The above lambda can be expressed as: li.sort(key=lambda li: li[1]), where the last two li are variable names, which can be taken as li.sort(key=lambda x: x[1])
Finally, let's explain this sentence:

# 根据字符串中不同字母的数量对一个字符串集合进行排序
strings.sort(key=lambda x: len(set(list(x))))

Sort a string set according to the number of different letters of the string. The number of different letters of the string can be thought of using the non-repeatability of the set set, so I thought of using the len function to find the length of the set set, and then sort by length. can. The value assigned to x here is each element in strings (the role of the key parameter).
Okay, let’s stop here, I hope you can gain something~

Guess you like

Origin blog.csdn.net/qq_40169189/article/details/108070945