请列举python中sorted函数中的key参数的具体用法
时间: 2023-08-30 07:12:15 浏览: 102
sorted函数中的key参数可以用于指定一个函数,该函数将应用于每个元素以生成排序用的键。以下是一些key参数的具体用法:
1. 按元素长度排序:
```
lst = ['apple', 'banana', 'kiwi', 'orange']
sorted_lst = sorted(lst, key=len)
# sorted_lst: ['kiwi', 'apple', 'banana', 'orange']
```
2. 按元素大小写排序:
```
lst = ['Apple', 'banana', 'Kiwi', 'orange']
sorted_lst = sorted(lst, key=str.lower)
# sorted_lst: ['Apple', 'banana', 'Kiwi', 'orange']
```
3. 按元素的第二个值排序:
```
lst = [(2, 'apple'), (1, 'banana'), (3, 'kiwi')]
sorted_lst = sorted(lst, key=lambda x: x[1])
# sorted_lst: [(2, 'apple'), (1, 'banana'), (3, 'kiwi')]
```
4. 按元素的多个值排序:
```
lst = [(2, 'apple'), (1, 'banana'), (3, 'kiwi'), (1, 'orange')]
sorted_lst = sorted(lst, key=lambda x: (x[0], x[1]))
# sorted_lst: [(1, 'banana'), (1, 'orange'), (2, 'apple'), (3, 'kiwi')]
```
5. 按元素的属性排序:
```
class Fruit:
def __init__(self, name, price):
self.name = name
self.price = price
lst = [Fruit('apple', 2), Fruit('banana', 1), Fruit('kiwi', 3)]
sorted_lst = sorted(lst, key=lambda x: x.price)
# sorted_lst: [Fruit('banana', 1), Fruit('apple', 2), Fruit('kiwi', 3)]
```
阅读全文