欢迎访问宙启技术站
智能推送

Python中的sorted函数:用于对列表或元组中的元素进行排序,并返回新的列表。

发布时间:2023-08-01 15:07:05

Python中的sorted函数是一个内置函数,用于对列表或元组中的元素进行排序,并返回一个新的已排序的列表。

sorted函数的基本语法如下:

sorted(iterable, key=None, reverse=False)

其中,iterable表示需要排序的列表或元组;key是一个可选的参数,用于指定排序时所使用的函数;reverse是一个可选的参数,用于决定是按升序还是降序排序,默认为False,即按升序排序。

当使用sorted函数进行排序时,它会将原始的列表或元组复制一份,并对复制后的副本进行排序,而不会改变原始的数据结构。

下面是一些使用sorted函数的示例:

1. 对数字列表进行升序排序:

numbers = [5, 2, 9, 1, 4]

sorted_numbers = sorted(numbers)

print(sorted_numbers)   # Output: [1, 2, 4, 5, 9]

2. 对字符串列表进行按字母升序排序:

fruits = ["apple", "banana", "cherry", "date"]

sorted_fruits = sorted(fruits)

print(sorted_fruits)   # Output: ['apple', 'banana', 'cherry', 'date']

3. 对字符串列表按长度进行升序排序:

fruits = ["apple", "banana", "cherry", "date"]

sorted_fruits = sorted(fruits, key=len)

print(sorted_fruits)   # Output: ['date', 'apple', 'cherry', 'banana']

4. 对字符串列表按照逆序进行降序排序:

fruits = ["apple", "banana", "cherry", "date"]

sorted_fruits = sorted(fruits, reverse=True)

print(sorted_fruits)   # Output: ['date', 'cherry', 'banana', 'apple']

需要注意的是,sorted函数返回一个新的已排序的列表,而不会改变原始的数据结构。如果要对原始的数据进行排序,可以使用列表的sort方法。

总结来说,Python中的sorted函数是对列表或元组中的元素进行排序的函数,通过指定可选参数来决定排序规则,并返回一个新的已排序的列表。