Python sorted() 函数用法

2023-09-17 22:29:10

sorted() 方法从指定的可迭代对象(stringlisttupleset)返回排序列表。

语法:

sorted(iterable, key, reverse)

参数:

可迭代
  1. :按升序或降序排列的可迭代对象。
  2. key:(可选)用作排序比较键的函数。
  3. 反向:(可选)如果为 true,则按降序排序。

返回值:

返回包含已排序项的列表对象。

下面的示例返回可迭代元素的排序列表。

nums = [2,1,5,3,4]
asc_nums = sorted(nums)
dsc_nums = sorted(nums, reverse = True)
print("Ascending Numbers: ", asc_nums)
print("Descending Numbers: ", dsc_nums)
nums_tuple = (8,7,6,10,9)
asc_nums = sorted(nums_tuple)
dsc_nums = sorted(nums_tuple, reverse = True)
print("Ascending Numbers: ", asc_nums)
print("Descending Numbers: ", dsc_nums)
mystr = 'gcadbfe'
asc_str = sorted(mystr)
dsc_str = sorted(mystr, reverse = True)
print("Ascending String: ", asc_str)
print("Reversed String: ", dsc_str)

输出:

Ascending Numbers: [1, 2, 3, 4, 5]
Descending Numbers: [5, 4, 3, 2, 1]
Ascending Numbers: [6, 7, 8, 9, 10]
Descending Numbers: [10, 9, 8, 7, 6] 
Ascending String: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
Reversed String: ['g', 'f', 'e', 'd', 'c', 'b', 'a']

上面,sorted() 方法从传递的可迭代对象列表、元组和字符串中返回列表对象。 reverse = True 参数以相反的顺序对可迭代对象进行排序。

sorted()方法提取指定dictionary的键并返回排序列表,如下所示。

numdict = {1:'One',3:'Three', 2:'Two'}
asc_nums = sorted(numdict)
dsc_nums = sorted(numdict, reverse=True)
print("Ascending List: ", asc_nums)
print("Descending List: ", dsc_nums)

输出:

Ascending List: [1, 2, 3]
Ascending List: [3, 2, 1]

使用自定义函数作为键进行排序(Sort using Custom Function as Key)

key 参数可用于根据不同的函数对可迭代对象进行排序。

numstr = ('One','Two','Three','Four')
asc_nums = sorted(numstr, key=len)
dsc_nums = sorted(numstr, key=len, reverse=True)
print("Ascending List: ", asc_nums)
print("Descending List: ", dsc_nums)

输出:

Ascending List: ['Four', 'One', 'Three', 'Two']
Descending List: ['Two', 'Three', 'One', 'Four']

您可以使用 set user-defined functionlambda function 来设置键参数。例如,下面按字符串的最后一个字符对字符串列表进行排序。

def getlastchar(s):
	return s[len(s)-1]
     
code = ('bb','cd', 'aa', 'zc')
asc_code = sorted(code, key=getlastchar) # using user-defined function
dsc_code = sorted(code, key=getlastchar, reverse=True)
print("Ascending Code: ", asc_code)
print("Descending Code: ", dsc_code)
print('----Using lambda function----')
asc_code = sorted(code, key=lambda s: s[len(s)-1]) # using lambda function
dsc_code = sorted(code, key=lambda s: s[len(s)-1], reverse=True)
print("Ascending Code: ", asc_code)
print("Descending Code: ", dsc_code)

输出:

Ascending Code: ['aa', 'bb', 'zc', 'cd']
Descending Code: ['cd', 'zc', 'bb', 'aa']
----Using lambda function----
Ascending Code: ['aa', 'bb', 'zc', 'cd']
Descending Code: ['cd', 'zc', 'bb', 'aa']

本文内容总结: