Sorted() function in Python
I was working on a ner project today. When processing the tags, I used a sorted function, but I found it would not be used. . .
Record: sorted(list, key, reverse)
list is a given list;
key is a function called by the sorting process, which is the sorting basis;
reverse is descending order or ascending order, the default is False ascending order, True descending order
To give a few examples:
1. Sort according to the absolute value of each value in the list
a1 = [1, 3, 5, -2, -4, -6]
a2 = sorted(l1, key=abs)
print(a1)
print(a2)
#输出结果
[1, 3, 5, -2, -4, -6]
[1, -2, 3, -4, 5, -6]
2. Sort according to the length of each element in the list
a = [[1,2], [3,4,5,6], (7,), '123']
print(sorted(a,key=len))
#输出结果
[(7,), [1, 2], '123', [3, 4, 5, 6]]
3. Descending order according to word frequency (used more)
word_dict = {
'apple':20, 'love':15}
sorted_word_dict = sorted(word_dict.items(), key=lambda d:d[1])
print(sorted_word_dict)
#输出结果
[('love', 15), ('apple', 20)]
sorted(d.items(), key=lambda x: x[1]) where d.items() is the object to be sorted; key=lambda x: x[1] is the second-dimensional data in the previous object (Ie value) values are sorted. key=lambda variable: variable [dimension]. The number of dimensions can be set according to your needs.
Note: The output of word_dict.items() is –>[(apple, 20), (love, 15)]