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

Python中的sorted()函数:使用和示例

发布时间:2023-05-28 03:38:53

Python中的sorted()函数是用于对可迭代对象进行排序的函数。它返回一个新的已排序列表,而不会修改原来的列表。

使用方式:

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

参数说明:

- iterable: 待排序的可迭代对象,如list、tuple、dict、set、str等。

- key: 排序的关键字,可以为函数或lambda表达式。

- reverse: 排序规则,reverse = True 表示降序,reverse = False 表示升序(默认)。

示例:

1. 列表排序

nums = [9, 3, 6, 2, 7, 1]
sorted_nums = sorted(nums)
print(sorted_nums)

# 输出:[1, 2, 3, 6, 7, 9]

2. 字符串排序

words = ["apple", "banana", "orange", "blueberry"]
sorted_words = sorted(words)
print(sorted_words)

# 输出:['apple', 'banana', 'blueberry', 'orange']

3. 排序规则

words = ["apple", "banana", "orange", "blueberry"]
sorted_words = sorted(words, key=len)  # 按单词长度排序
print(sorted_words)

# 输出:['apple', 'banana', 'orange', 'blueberry']


nums = [9, 3, 6, 2, 7, 1]
sorted_nums = sorted(nums, reverse=True) # 降序排序
print(sorted_nums)

# 输出:[9, 7, 6, 3, 2, 1]

4. 字典排序

scores = {"Alice": 95, "Bob": 80, "Cindy": 90, "David": 75}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)

# 输出:[('Alice', 95), ('Cindy', 90), ('Bob', 80), ('David', 75)]

以上是sorted()函数的使用示例,可以看出,sorted()函数非常灵活,可以对不同类型的数据进行排序,通过指定key和reverse参数,可以实现不同排序规则。