高效排序数据
本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 48 课,共 78 课。
排序是计算机科学中的一项基础操作,Python 提供了强大的内置工具,可以高效地对数据进行排序。用于排序的主要函数是 sorted(),它可以对各种类型的数据进行排序,包括数字、字符串和更复杂的对象。
基础排序:
sorted() 函数接受一个可迭代对象(例如列表、元组或集合)作为参数,并返回一个包含排序后元素的新列表。默认情况下,它按升序排序。
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# 输出:[1, 1, 2, 3, 4, 5, 6, 9]在这个示例中,sorted() 会按升序对 numbers 列表进行排序。
反向排序:
要按降序排序,可以使用 reverse 参数,并将其设置为 True。
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)
# 输出:[9, 6, 5, 4, 3, 2, 1, 1]这里,sorted() 会按降序排列 numbers 列表。
字符串排序:
sorted() 函数也可以根据字典序(也就是字符串在词典中出现的顺序)对字符串进行排序。
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words)
print(sorted_words)
# 输出:['apple', 'banana', 'cherry']在这个示例中,sorted() 会按字母顺序对 words 列表进行排序。
使用键函数进行自定义排序:
对于更复杂的排序需求,你可以使用 key 参数指定一个用于确定排序顺序的函数。排序前,系统会将 key 函数应用于每个元素,并使用返回值进行比较。
words = ["banana", "kiwi", "fig"]
sorted_words_by_length = sorted(words, key=len)
print(sorted_words_by_length)
# 输出:['fig', 'kiwi', 'banana']在这种情况下,sorted() 会根据每个单词的长度对 words 列表排序,并使用 len() 函数作为 key。
挑战
简单使用 sorted() 函数编写一个程序,完成以下排序任务:
- 将一个数字列表按升序排序。
- 将同一个数字列表按降序排序。
- 将一个字符串列表按字母顺序排序。
- 根据长度对同一个字符串列表排序。
亲手试试
# 初始输入
numbers = [5, 3, 8, 1, 2]
words = ["elephant", "cat", "dolphin", "bee"]
# 任务 1:将数字按升序排序
# 任务 2:将数字按降序排序
# 任务 3:将单词按字母顺序排序
# 任务 4:将单词按长度排序
# 用你为每个任务编写的代码替换 'None'
ascending_numbers = None
descending_numbers = None
alphabetical_words = None
length_sorted_words = None
# 打印结果
print("Ascending:", ascending_numbers)
print("Descending:", descending_numbers)
print("Alphabetical:", alphabetical_words)
print("By Length:", length_sorted_words)这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: Python 在线编译器