English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
sort()方法对给定列表的元素进行排序。
sort()方法以特定顺序(升序或降序)对给定列表的元素进行排序。
sort()方法的语法为:
list.sort(key=..., reverse=...)
另外,您也可以出于相同的目的使用Python的内置函数sorted()。
sorted(list, key=..., reverse=...)
注意: sort()和sorted()之间最简单的区别是:sort()不返回任何值,而sorted()返回可迭代的列表。
默认情况下,sort()不需要任何其他参数。但是,它有两个可选参数:
reverse -如果为true,则排序后的列表将反转(或以降序排序)
key -用作排序比较键的函数
sort()方法不返回任何值。相反,它将更改原始列表。
如果要原始列表,请使用sorted()。
# Vowel list vowels = ['e', 'a', 'u', 'o', 'i'] # Sort the vowels vowels.sort() # Print vowels print('Sorted list:', vowels)
When running the program, the output is:
Sorted list: ['a', 'e', 'i', 'o', 'u']
The sort() method accepts a reverse parameter as an optional parameter.
Setting reverse=True sorts the list in descending order.
list.sort(reverse=True)
Or, for sorted(), you can use the following code.
sorted(list, reverse=True)
# Vowel list vowels = ['e', 'a', 'u', 'o', 'i'] # Vowel sorting vowels.sort(reverse=True) # Print vowels print('Sorted list (in descending order):', vowels)
When running the program, the output is:
Sorted list (in descending order): ['u', 'o', 'i', 'e', 'a']
If you want to sort using your own method, sort() can also take the key function as an optional parameter.
The list can be sorted according to the result of the key function.
list.sort(key=len)
It can also be sorted
sorted(list, key=len)
Here, len is a built-in function of Python, used to calculate the length of an element.
This list is sorted according to the length of each element (from the lowest to the highest count).
# Sort by the second element def takeSecond(elem): return elem[1)] # Random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # Key sort list random.sort(key=takeSecond) # Print the list print('Sorted list:', random)
When running the program, the output is:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]