如何给列表中的元素排序
时间: 2023-12-01 08:03:02 浏览: 30
Python 中可以使用 `sorted()` 函数或列表的 `sort()` 方法对列表中的元素进行排序。
`sorted()` 函数可以对任何可迭代对象进行排序,包括列表、元组、集合、字典等,它会返回一个新的排序后的列表,原来的列表不会受到影响。例如:
```python
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
`sort()` 方法是列表特有的方法,它会对原列表进行排序。例如:
```python
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
这两种方法都可以接受一个关键字参数,用于指定排序规则。例如,要按照元素长度进行排序,可以这样做:
```python
my_list = ['apple', 'banana', 'orange', 'pear', 'grape']
sorted_list = sorted(my_list, key=len)
print(sorted_list) # 输出:['pear', 'apple', 'grape', 'banana', 'orange']
my_list.sort(key=len)
print(my_list) # 输出:['pear', 'apple', 'grape', 'banana', 'orange']
```
以上代码会按照元素长度升序排列列表中的元素。