1 回答

TA贡献1868条经验 获得超4个赞
您可以将查询转换为字典列表,然后使用运算符模块的itemgetter函数根据一个或多个字典值对条目进行排序。
假设您有以下列表:
posts_list = [
{'post_id':100, 'author_name': 'John', 'date_posted':'2019-02-14', 'expiry_date':'2019-09-20'},
{'post_id':101, 'author_name': 'Bob', 'date_posted':'2019-03-15', 'expiry_date':'2019-04-25'},
{'post_id':102, 'author_name': 'Alice', 'date_posted':'2019-01-16', 'expiry_date':'2019-07-24'},
{'post_id':103, 'author_name': 'Eric', 'date_posted':'2019-04-14', 'expiry_date':'2019-05-20'}
]
输出按所有字典共有的任何字段排序的这些行非常容易。
例子:
from operator import itemgetter
list_by_author_name = sorted(posts_list, key=itemgetter('author_name'))
list_by_date_posted = sorted(posts_list, key=itemgetter('date_posted'))
list_by_expiry_date = sorted(posts_list, key=itemgetter('expiry_date'))
print(list_by_author_name)
print(list_by_date_posted)
print(list_by_expiry_date)
产生以下结果:
[
{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'},
{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'},
{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'},
{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'}
]
[
{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'},
{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'},
{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'},
{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'}
]
[
{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'},
{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'},
{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'},
{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'}
]
添加回答
举报