Python3 sorted() Function
Description
The sorted() function sorts any iterable object.
>
Difference between sort and sorted:
sort is a method applied to lists, while sorted can sort any iterable object.
The sort method modifies the existing list, whereas the built-in sorted function returns a new list, without altering the original.
Syntax
Syntax for sorted:
sorted(iterable, key=None, reverse=False)
Parameter descriptions:
iterable -- An iterable object.
key -- A function used for comparison, taking a single argument, derived from the iterable, specifying a single element from the iterable for sorting.
reverse -- Sorting order; reverse = True for descending, reverse = False for ascending (default).
Return Value
Returns a newly sorted list.
Example
The following example demonstrates the simplest use of sorted:
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5] # Default is ascending
You can also use the list.sort() method of a list. This method modifies the original list (returns None). Generally, this method is less convenient than sorted() - if you do not need the original list, list.sort() is slightly more efficient.
>>> a=[5,2,3,1,4]
>>> a.sort()
>>> a
[1,2,3,4,5]
Another difference is that the list.sort() method is defined only for lists. The sorted() function can accept any iterable.
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
Sorting in reverse order using a key:
>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> 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, pass the third parameter reverse=True:
>>> example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> sorted(example_list, reverse=True)
[7, 6, 5, 4, 3, 2, 1, 0]
Here is a more complex example, sorting a medal table with data for 15 countries, using \n
as a delimiter:
Example
s = "Germany 10 11 16\nItaly 10 10 20\nNetherlands 10 12 14\nFrance 10 12 11\nUK 22 21 22\nChina 38 32 18\nJapan 27 14 17\nUSA 39 41 33\nROC 20 28 23\nAustralia 17 7 22\nHungary 6 7 7\nCanada 7 6 11\nCuba 7 3 5\nBrazil 7 6 8\nNew Zealand 7 6 7"
stodata = s.split('\n',-1)
# Using sorted
para = {}
for line in range(len(stodata)):
# Each line of data
data = stodata[line].split(' ')
print(data)
# Assemble data structure para={'China': [], 'Russia': []}
para[data[0]] = [int('-' + i) for i in data[1:]]
# Start sorting (x[1] represents medal count, x[0] represents country)
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]}")
Output:
['Germany', '10', '11', '16']
['Italy', '10', '10', '20']
['Netherlands', '10', '12', '14']
['France', '10', '12', '11']
['United Kingdom', '22', '21', '22'] ['China', '38', '32', '18'] ['Japan', '27', '14', '17'] ['USA', '39', '41', '33'] ['ROC (Russia)', '20', '28', '23'] ['Australia', '17', '7', '22'] ['Hungary', '6', '7', '7'] ['Canada', '7', '6', '11'] ['Cuba', '7', '3', '5'] ['Brazil', '7', '6', '8'] ['New Zealand', '7', '6', '7']
1 USA 2 China 3 Japan 4 United Kingdom 5 ROC (Russia) 6 Australia 7 Netherlands 8 France 9 Germany 10 Italy 11 Canada 12 Brazil 13 New Zealand 14 Cuba 15 Hungary