新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:如何在Python中對dicts列表進(jìn)行排序
問題:在使用MongoDB組合函數(shù)(它類似于SQL的GROUP BY)來聚合項(xiàng)目的一些結(jié)果。此功能雖然非??幔粫Ψ纸M數(shù)據(jù)進(jìn)行排序。

解決:以下是如何對數(shù)據(jù)進(jìn)行排序。(它只有一行python,但很難記住如何做到這一點(diǎn)。)
DATA是mongoDB組函數(shù)的輸出。我想按照這個列表來排序'ups_ad'。
from pprint import pprintDATA = [
{u'avg': 2.9165000000000001,
u'count': 10.0,
u'total': 29.165000000000003,
u'ups_ad': u'10.194.154.49:80'},
{u'avg': 2.6931000000000003,
u'count': 10.0,
u'total': 26.931000000000001,
u'ups_ad': u'10.194.155.176:80'},
{u'avg': 1.9860909090909091,
u'count': 11.0,
u'total': 21.847000000000001,
u'ups_ad': u'10.195.71.146:80'},
{u'avg': 1.742818181818182,
u'count': 11.0,
u'total': 19.171000000000003,
u'ups_ad': u'10.194.155.48:80'}
]data_sorted = sorted(DATA, key=lambda item: item['ups_ad'])pprint(data_sorted)結(jié)果:
[{u'avg': 2.9165000000000001,
u'count': 10.0,
u'total': 29.165000000000003,
u'ups_ad': u'10.194.154.49:80'},
{u'avg': 2.6931000000000003,
u'count': 10.0,
u'total': 26.931000000000001,
u'ups_ad': u'10.194.155.176:80'},
{u'avg': 1.742818181818182,
u'count': 11.0,
u'total': 19.171000000000003,
u'ups_ad': u'10.194.155.48:80'},
{u'avg': 1.9860909090909091,
u'count': 11.0,
u'total': 21.847000000000001,
u'ups_ad': u'10.195.71.146:80'}]參考文獻(xiàn):
HowTo / Sorting - PythonInfo Wiki
排序的內(nèi)置函數(shù) - Python文檔
網(wǎng)頁標(biāo)題:創(chuàng)新互聯(lián)Python教程:如何在Python中對dicts列表進(jìn)行排序
文章轉(zhuǎn)載:http://fisionsoft.com.cn/article/ccohcco.html


咨詢
建站咨詢
