sorted函数用法
时间: 2023-11-11 11:57:46 浏览: 33
Python中的sorted函数是用于对可迭代对象进行排序的函数,可以按照升序或降序进行排序,并且不会改变原有的可迭代对象,而是返回一个新的已排序的列表。
sorted函数的语法如下:
```
sorted(iterable, key=None, reverse=False)
```
其中,iterable表示要排序的可迭代对象;key是一个可选的参数,用于指定一个函数来自定义排序规则;reverse表示排序顺序,True表示降序,False表示升序,默认为False。
下面是一个示例:
```python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
reverse_sorted_numbers = sorted(numbers, reverse=True)
print(reverse_sorted_numbers) # 输出:[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
```
如果要按照自定义的排序规则进行排序,可以使用key参数,用于指定一个函数来生成一个排序关键字,例如按照字符串长度进行排序:
```python
strings = ['cat', 'window', 'defenestrate']
sorted_strings = sorted(strings, key=len)
print(sorted_strings) # 输出:['cat', 'window', 'defenestrate']
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)