Python3 sorted() Function
Description
sorted()The function performs sorting operations on all iterable objects.
Difference between sort and sorted:
sort is a method applied to lists, while sorted can perform sorting operations on all iterable objects.
The list sort method operates on an existing list, while the built-in function sorted returns a new list, rather than operating on the original.
Syntax
sorted syntax:
sorted(iterable, key=None, reverse=False)
Parameter description:
- iterable -- iterable object.
- key -- mainly used to compare elements, has only one parameter. The specific function's parameter is taken from the iterable object, specifying an element in the iterable object to be used for sorting.
- reverse -- sorting rule, reverse = True for descending order, reverse = False for ascending order (default).
Return Value
Returns a re-sorted list.
Example
The following example demonstrates the simplest usage of sorted:
[1, 2, 3, 4, 5] # default is ascending order
You can also use the list.sort() method of a list. This method modifies the original list (returns None). Usually this method is less convenient than sorted() - if you don't need the original list, list.sort() is slightly more efficient.
>>> a.sort()
>>> a
[1,2,3,4,5]
Another difference is that the list.sort() method is only defined for lists, while the sorted() function can accept any iterable.
[1, 2, 3, 4, 5]
Use key to sort in reverse order
>>> result_list = sorted(example_list, key=lambda x: x*-1)
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
>>>
To sort in reverse order, you can also pass the third parameter reverse=True:
>>> sorted(example_list, reverse=True)
[7, 6, 5, 4, 3, 2, 1, 0]
The following is a more complex example, sorting the medal table. The data contains gold, silver, and bronze data for 15 countries, using\nas the delimiter:
Example
stodata = s.split('\n',-1)
# Use sorted
para = {}
for line in range(len(stodata)):
# Each row of data
data = stodata[line].split(' ')
print(data)
# Assemble the data structure para={'China': [], 'Russia': []}
para[data[0]] = [int('-' + i) for i in data[1:]]
# Start sorting (x
new_para = sorted(para.items(), key=lambda x: (x[1], x[0]))
print()
c=[]
for i in new_para:
c.append((i[0]))
for j in range(15):
print(f"{(j+1):2d} {c[j]}")
The output result is:
['德国', '10', '11', '16'] ['意大利', '10', '10', '20'] ['荷兰', '10', '12', '14'] ['法国', '10', '12', '11'] ['英国', '22', '21', '22'] ['中国', '38', '32', '18'] ['日本', '27', '14', '17'] ['美国', '39', '41', '33'] ['俄罗斯奥委会', '20', '28', '23'] ['澳大利亚', '17', '7', '22'] ['匈牙利', '6', '7', '7'] ['加拿大', '7', '6', '11'] ['古巴', '7', '3', '5'] ['巴西', '7', '6', '8'] ['新西兰', '7', '6', '7'] 1 美国 2 中国 3 日本 4 英国 5 俄罗斯奥委会 6 澳大利亚 7 荷兰 8 法国 9 德国 10 意大利 11 加拿大 12 巴西 13 新西兰 14 古巴 15 匈牙利Other Extensions
Python3 Built-in Functions