Python中的 Sorted()函数
Python sorted()函数从可迭代对象返回一个排序列表。
Sorted() 对任何序列(列表、元组)进行排序,并始终以排序方式返回包含元素的列表,而不修改原始序列。
Syntax: sorted(iterable, key, reverse)
Parameters: sorted takes three parameters from which two are optional.
- Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
- Key(optional) : A function that would server as a key or a basis of sort comparison.
- Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
Python sorted()函数示例
示例 1: Python sorted() 列表
Python3
x = [2, 8, 1, 4, 6, 3, 7]
print("Sorted List returned :"),
print(sorted(x))
print("\nReverse sort :"),
print(sorted(x, reverse=True))
print("\nOriginal list not modified :"),
print(x)
Python3
# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
# String-sorted based on ASCII translations
x = "python"
print(sorted(x))
# Dictionary
x = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
print(sorted(x))
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))
Python3
# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = ''.join(sorted(test_string, reverse = True))
# print result
print("String after reverse sorting : " + str(res))
Python3
# Python code to demonstrate
# Reverse Sort a String
# using sorted() + reduce() + lambda
# import the module
import functools
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
# Reverse Sort a String
res = functools.reduce(lambda x, y: x + y,
sorted(test_string,
reverse=True))
# print result
print("String after reverse sorting : " + str(res))
Python3
L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))
Python3
# Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
return x % 7
L = [15, 3, 11, 7]
print("Normal sort :", sorted(L))
print("Sorted with key:", sorted(L, key=func))
输出:
Sorted List returned : [1, 2, 3, 4, 6, 7, 8]
Reverse sort : [8, 7, 6, 4, 3, 2, 1]
Original list not modified : [2, 8, 1, 4, 6, 3, 7]
示例 2:对不同的数据类型进行排序
Python3
# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
# String-sorted based on ASCII translations
x = "python"
print(sorted(x))
# Dictionary
x = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
print(sorted(x))
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))
输出:
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['h', 'n', 'o', 'p', 't', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
示例 3: Python反向排序
Python3
# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = ''.join(sorted(test_string, reverse = True))
# print result
print("String after reverse sorting : " + str(res))
输出:
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee
示例 4: Python sorted() lambda
Python3
# Python code to demonstrate
# Reverse Sort a String
# using sorted() + reduce() + lambda
# import the module
import functools
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
# Reverse Sort a String
res = functools.reduce(lambda x, y: x + y,
sorted(test_string,
reverse=True))
# print result
print("String after reverse sorting : " + str(res))
输出:
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee
Python sorted() 键
sorted()函数有一个名为“key”的可选参数,它将一个函数作为其值。此键函数在排序之前转换每个元素,它获取值并返回 1 值,然后在排序中使用该值而不是原始值。例如,如果我们在 sorted() 中传递一个字符串列表,它会按字母顺序排序。但是如果我们指定key = len,即给len函数作为key,那么字符串会被传递给len,并且它返回的值,即字符串的长度会被排序。这意味着字符串将根据它们的长度进行排序
Python3
L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))
输出:
Normal sort : ['aaa', 'b', 'cccc', 'dd']
Sort with len : ['b', 'dd', 'aaa', 'cccc']
Key 也可以将用户定义的函数作为其值作为排序的依据。
Python3
# Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
return x % 7
L = [15, 3, 11, 7]
print("Normal sort :", sorted(L))
print("Sorted with key:", sorted(L, key=func))
输出:
Normal sort : [3, 7, 11, 15]
Sorted with key: [7, 15, 3, 11]