python的sorted是什么 · The Chat Archivepython的sorted是什么
Download ▾
From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with
gemini-2.5-pro’s answer.
Assistant在 Python 中, 是一个,用于对,并返回一个新的,原始数据不会被修改。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
sorted()
内置函数
可迭代对象(如列表、元组、字符串等)进行排序
排好序的列表
📌 基本语法:
sorted(iterable, *, key=None, reverse=False)
参数说明:
| 参数名 | 类型/说明 |
|---|
iterable | 要排序的可迭代对象(如列表、元组、字符串等) |
key | 可选参数。指定一个函数,该函数会作用于每个元素上,根据其返回值进行排序(例如按长度、绝对值等)。 |
reverse | 可选布尔值。如果为 True,则按降序排序;默认是升序。 |
✅ 示例讲解
1. 对数字列表排序:
nums = [5, 2, 9, 1]
sorted_nums = sorted(nums)
print(sorted_nums) # 输出: [1, 2, 5, 9]
2. 对字符串排序(按字母顺序):
words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words)
print(sorted_words) # 输出: ['apple', 'banana', 'cherry']
3. 降序排序(使用 reverse=True):
nums = [5, 2, 9, 1]
sorted_desc = sorted(nums, reverse=True)
print(sorted_desc) # 输出: [9, 5, 2, 1]
4. 使用 key 自定义排序规则:
a. 按字符串长度排序:
words = ['apple', 'fig', 'banana']
sorted_by_len = sorted(words, key=len)
print(sorted_by_len) # 输出: ['fig', 'apple', 'banana']
b. 按元组中的某个字段排序:
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
# 按年龄排序
sorted_by_age = sorted(people, key=lambda x: x[1])
print(sorted_by_age)
# 输出: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
c. 忽略大小写排序字符串:
words = ['Apple', 'banana', 'Cherry']
sorted_case_insensitive = sorted(words, key=str.lower)
print(sorted_case_insensitive) # 输出: ['Apple', 'banana', 'Cherry']
⚠️ 注意事项:
sorted() 总是返回一个列表,即使你传入的是元组或字符串。
- 如果你想原地排序(修改原始列表),可以使用列表的
.sort() 方法:
my_list = [5, 2, 9, 1]
my_list.sort()
print(my_list) # 输出: [1, 2, 5, 9]
🔁 和 list.sort() 的区别:
| 特点 | sorted() | list.sort() |
|---|
| 是否改变原数据 | 否(返回新列表) | 是(原地修改) |
| 返回值 | 排好序的新列表 | 无(返回 None) |
| 适用类型 | 所有可迭代对象 | 只适用于列表 |
总结
sorted() 是 Python 中非常实用的排序工具,灵活且安全(不修改原始数据),配合 key 和 reverse 参数可以实现各种复杂的排序需求。
如果你还想了解如何对自定义对象排序、多条件排序等内容,也可以继续问我 😊