Files
Python_CookBook_repo/1.数据结构与算法/13.字典公共键排序.py
2025-09-10 16:12:45 +08:00

26 lines
833 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 我们有一个字典列表,想要按照字典里的某些键对列表进行排序
# 字典列表如下:
rows = [
{"fname":"Brian", "lname": "Jones", "uid":1003},
{"fname":"David", "lname": "Beazley", "uid":1002},
{"fname":"John", "lname": "Cleese", "uid":1001},
{"fname":"Big", "lname": "Jones", "uid":1004}
]
# 这时候用到itemgetter模块
from operator import itemgetter
# itemgetter的主要功能是通过可查询的标记进行数据获取;
# 下面分别根据fname和uid进行数据获取
rows_by_fname = sorted(rows, key=itemgetter("fname"))
rows_by_uid = sorted(rows, key=itemgetter("uid"))
print(rows_by_fname)
print(rows_by_uid)
# 当然itemgetter也能被lambda函数替代替代操作如下
rows_by_fname_v2 = sorted(rows, key= lambda row: row["fname"])
print(rows_by_fname_v2)