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'}
]
添加回答
舉報