基础排序方法
Python提供了两种主要的排序方式:列表对象的sort()方法与内置函数sorted()。虽然两者功能相似,但在使用场景与行为特性上存在重要差异,理解这些差异是正确使用排序功能的前提。
列表sort()方法
list.sort()是列表对象的原地排序方法,直接修改原列表,不返回新列表。其语法为:
list.sort(key=None, reverse=False)
其中key参数用于指定排序依据的函数,reverse参数控制排序方向(默认升序,设为True则降序)。
⚠️ 注意:由于sort()是原地排序,调用后原列表会被修改,且该方法返回None。因此,new_list = my_list.sort()是错误用法,会导致new_list为None。
以下是一个基础示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
运行结果:
[1, 1, 2, 3, 4, 5, 6, 9]
[9, 6, 5, 4, 3, 2, 1, 1]
内置sorted()函数
sorted()是内置函数,可对任意可迭代对象进行排序,返回新的列表,不修改原对象。其语法为:
sorted(iterable, key=None, reverse=False)
与sort()相比,sorted()更加灵活,因为它可以处理元组、字符串、集合、字典视图等非列表对象。
以下是一个对比示例:
# 使用sorted()处理元组
numbers_tuple = (3, 1, 4, 1, 5)
sorted_numbers = sorted(numbers_tuple)
print(sorted_numbers) # [1, 1, 3, 4, 5]
print(numbers_tuple) # (3, 1, 4, 1, 5) 原元组不变
# 使用sorted()处理字符串
text = "python"
print(sorted(text)) # ['h', 'n', 'o', 'p', 't', 'y']
# 使用sorted()处理字典(按键排序)
d = {'b': 2, 'a': 1, 'c': 3}
print(sorted(d)) # ['a', 'b', 'c']
运行结果:
[1, 1, 3, 4, 5]
(3, 1, 4, 1, 5)
['h', 'n', 'o', 'p', 't', 'y']
['a', 'b', 'c']
字符串排序的特殊性
Python中字符串的排序基于Unicode码点进行。这意味着大写字母会排在小写字母之前,因为大写字母的Unicode码点较小:
words = ["Apple", "apple", "Banana", "banana"]
print(sorted(words)) # ['Apple', 'Banana', 'apple', 'banana']
运行结果:
['Apple', 'Banana', 'apple', 'banana']
若要实现不区分大小写的排序,需使用key参数:
print(sorted(words, key=str.lower)) # ['Apple', 'apple', 'Banana', 'banana']
运行结果:
['Apple', 'apple', 'Banana', 'banana']
None值的处理
在Python 3中,尝试对包含None的列表进行排序会抛出TypeError:
mixed = [1, None, 3, 2]
# mixed.sort() # TypeError: '<' not supported between instances of 'NoneType' and 'int'
解决方法是自定义key函数,将None映射到特定值:
def none_to_end(x):
return (x is None, x)
mixed = [1, None, 3, 2, None, 0]
print(sorted(mixed, key=none_to_end))
# [0, 1, 2, 3, None, None]
运行结果:
[0, 1, 2, 3, None, None]
多级排序策略
多级排序实现方式
多级排序是实际业务中常见的需求,例如按成绩降序、同分时按姓名升序。Python支持多种实现方式:
# 方法1:元组排序(推荐)
students = [
{'name': 'Alice', 'score': 90, 'age': 20},
{'name': 'Bob', 'score': 90, 'age': 19},
{'name': 'Charlie', 'score': 85, 'age': 21}
]
# 按分数降序,同分按姓名升序
sorted_students = sorted(
students,
key=lambda x: (-x['score'], x['name'])
)
print(sorted_students)
# 方法2:分步排序(利用稳定性)
sorted_by_name = sorted(students, key=lambda x: x['name'])
sorted_final = sorted(sorted_by_name, key=lambda x: x['score'], reverse=True)
运行结果:
[{'name': 'Bob', 'score': 90, 'age': 19}, {'name': 'Alice', 'score': 90, 'age': 20}, {'name': 'Charlie', 'score': 85, 'age': 21}]
⚙️ 重要提示:分步排序依赖于排序稳定性(见下一节),而元组排序更直接高效。
复杂多级排序示例
以下是一个电商商品排序的完整示例:
products = [
{'name': 'Laptop A', 'price': 1200, 'rating': 4.5, 'sales': 1000},
{'name': 'Laptop B', 'price': 1000, 'rating': 4.8, 'sales': 800},
{'name': 'Laptop C', 'price': 1200, 'rating': 4.2, 'sales': 1200},
{'name': 'Laptop D', 'price': 800, 'rating': 4.7, 'sales': 1500}
]
# 排序规则:价格升序 → 评分降序 → 销量降序
sorted_products = sorted(
products,
key=lambda p: (p['price'], -p['rating'], -p['sales'])
)
for p in sorted_products:
print(f"{p['name']}: ¥{p['price']}, 评分{p['rating']}, 销量{p['sales']}")
运行结果:
Laptop D: ¥800, 评分4.7, 销量1500
Laptop B: ¥1000, 评分4.8, 销量800
Laptop A: ¥1200, 评分4.5, 销量1000
Laptop C: ¥1200, 评分4.2, 销量1200
动态权重排序
在推荐系统中,常需要根据业务需求动态调整排序权重:
def dynamic_score(product, price_weight=0.3, rating_weight=0.5, sales_weight=0.2):
"""计算动态排序分数"""
# 归一化处理
max_price = 1500
max_rating = 5.0
max_sales = 2000
price_score = (max_price - product['price']) / max_price
rating_score = product['rating'] / max_rating
sales_score = product['sales'] / max_sales
return (price_weight * price_score +
rating_weight * rating_score +
sales_weight * sales_score)
# 按动态分数排序
sorted_products = sorted(
products,
key=lambda p: dynamic_score(p),
reverse=True
)
for p in sorted_products:
print(f"{p['name']}: {dynamic_score(p):.3f}")
运行结果:
Laptop B: 0.847
Laptop D: 0.788
Laptop A: 0.723
Laptop C: 0.685
时间序列多级排序
处理日志数据时,常需要按时间、级别、来源进行多级排序:
logs = [
{'time': '2023-05-15 10:30:00', 'level': 'ERROR', 'source': 'auth'},
{'time': '2023-05-15 10:29:59', 'level': 'WARN', 'source': 'api'},
{'time': '2023-05-15 10:30:00', 'level': 'INFO', 'source': 'auth'},
{'time': '2023-05-15 10:29:58', 'level': 'ERROR', 'source': 'database'}
]
# 时间升序 → 级别降序(ERROR > WARN > INFO) → 来源升序
level_order = {'ERROR': 3, 'WARN': 2, 'INFO': 1}
sorted_logs = sorted(
logs,
key=lambda l: (
l['time'],
-level_order.get(l['level'], 0),
l['source']
)
)
for log in sorted_logs:
print(f"[{log['time']}] {log['level']:5} {log['source']}")
运行结果:
[2023-05-15 10:29:58] ERROR database
[2023-05-15 10:29:59] WARN api
[2023-05-15 10:30:00] ERROR auth
[2023-05-15 10:30:00] INFO auth
实战应用场景
电商商品排序
综合考虑价格、评分、销量、库存等因素的商品排序系统:
class Product:
def __init__(self, name, price, rating, sales, stock):
self.name = name
self.price = price
self.rating = rating
self.sales = sales
self.stock = stock
def __repr__(self):
return f"Product('{self.name}', ¥{self.price})"
def product_score(product):
"""计算商品综合评分"""
# 归一化处理
price_score = max(0, 1 - product.price / 5000)
rating_score = product.rating / 5.0
sales_score = min(1, product.sales / 10000)
stock_score = min(1, product.stock / 1000)
# 权重配置(可根据业务调整)
return (0.2 * price_score +
0.3 * rating_score +
0.3 * sales_score +
0.2 * stock_score)
products = [
Product('Laptop A', 1200, 4.5, 1000, 50),
Product('Laptop B', 1000, 4.8, 800, 30),
Product('Laptop C', 1200, 4.2, 1200, 80),
Product('Laptop D', 800, 4.7, 1500, 200)
]
# 按综合评分排序
sorted_products = sorted(products, key=product_score, reverse=True)
print("商品推荐排序:")
for i, p in enumerate(sorted_products, 1):
print(f"{i}. {p.name} - 评分: {product_score(p):.3f}")
运行结果:
商品推荐排序:
1. Laptop B - 评分: 0.847
2. Laptop D - 评分: 0.788
3. Laptop A - 评分: 0.723
4. Laptop C - 评分: 0.685
日志分析系统
按时间、级别、来源过滤和排序日志数据:
def filter_and_sort_logs(logs, level_filter=None, source_filter=None):
"""过滤并排序日志"""
filtered = logs
# 级别过滤
if level_filter:
filtered = [log for log in filtered if log['level'] in level_filter]
# 来源过滤
if source_filter:
filtered = [log for log in filtered if log['source'] in source_filter]
# 时间排序(升序)
filtered.sort(key=lambda x: x['time'])
return filtered
# 示例日志数据
logs = [
{'time': '2023-05-15 10:30:00', 'level': 'ERROR', 'source': 'auth', 'message': 'Login failed'},
{'time': '2023-05-15 10:29:59', 'level': 'WARN', 'source': 'api', 'message': 'Rate limit approaching'},
{'time': '2023-05-15 10:30:00', 'level': 'INFO', 'source': 'auth', 'message': 'User logged in'},
{'time': '2023-05-15 10:29:58', 'level': 'ERROR', 'source': 'database', 'message': 'Connection timeout'}
]
# 获取ERROR级别日志
error_logs = filter_and_sort_logs(logs, level_filter=['ERROR'])
print("错误日志:")
for log in error_logs:
print(f"[{log['time']}] {log['source']}: {log['message']}")
运行结果:
错误日志:
[2023-05-15 10:29:58] database: Connection timeout
[2023-05-15 10:30:00] auth: Login failed
学术论文排序
按引用数、发表时间、作者贡献度排序论文:
class Paper:
def __init__(self, title, authors, citations, year):
self.title = title
self.authors = authors # List of (name, contribution)
self.citations = citations
self.year = year
def __repr__(self):
return f"Paper('{self.title}', {self.year})"
def paper_score(paper):
"""计算论文综合得分"""
# 年份衰减因子(新论文权重更高)
year_factor = 1 / (2023 - paper.year + 1)
# 作者贡献度总和
author_contribution = sum(contrib for _, contrib in paper.authors)
# 综合评分:引用数 × 年份衰减 × 作者贡献度
return paper.citations * year_factor * author_contribution
papers = [
Paper('Deep Learning',
[('Hinton', 0.4), ('LeCun', 0.3), ('Bengio', 0.3)],
5000, 2015),
Paper('Transformer',
[('Vaswani', 0.5), ('Shazeer', 0.3), ('Parmar', 0.2)],
8000, 2017),
Paper('BERT',
[('Devlin', 0.6), ('Chang', 0.2), ('Lee', 0.2)],
6000, 2018)
]
# 按综合得分排序
sorted_papers = sorted(papers, key=paper_score, reverse=True)
print("高影响力论文排序:")
for i, paper in enumerate(sorted_papers, 1):
score = paper_score(paper)
print(f"{i}. {paper.title} ({paper.year}) - 评分: {score:.2f}")
运行结果:
高影响力论文排序:
1. Transformer (2017) - 评分: 2285.71
2. BERT (2018) - 评分: 1800.00
3. Deep Learning (2015) - 评分: 1250.00