亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

Python按照list dict key進行排序過程解析

瀏覽:19日期:2022-07-31 08:31:08

在做項目的時候,遇到這樣的數(shù)據(jù):

'trends': [{ 'name': 'Rick Gates', 'promoted_content': null, 'query': '%22Rick+Gates%22', 'tweet_volume': 135732, 'url': 'http://twitter.com/search?q=%22Rick+Gates%22'},{ 'name': '#TheBachelorette', 'promoted_content': null, 'query': '%23TheBachelorette', 'tweet_volume': 91245, 'url': 'http://twitter.com/search?q=%23TheBachelorette'},{ 'name': '#KremlinAnnex', 'promoted_content': null, 'query': '%23KremlinAnnex', 'tweet_volume': 42654, 'url': 'http://twitter.com/search?q=%23KremlinAnnex'},{ 'name': '#LHHH', 'promoted_content': null, 'query': '%23LHHH', 'tweet_volume': 35252, 'url': 'http://twitter.com/search?q=%23LHHH'}]

我需要做的就是根據(jù)tweet_volume的數(shù)值對trends里的元素進行排序。

實現(xiàn)代碼:

把上面數(shù)據(jù)以字典的方式獲取,相當(dāng)于把取出的就是后面的列表,即

trends=[{ 'name': 'Rick Gates', 'promoted_content': null, 'query': '%22Rick+Gates%22', 'tweet_volume': 135732, 'url': 'http://twitter.com/search?q=%22Rick+Gates%22'},{ 'name': '#TheBachelorette', 'promoted_content': null, 'query': '%23TheBachelorette', 'tweet_volume': 91245, 'url': 'http://twitter.com/search?q=%23TheBachelorette'},{ 'name': '#KremlinAnnex', 'promoted_content': null, 'query': '%23KremlinAnnex', 'tweet_volume': 42654, 'url': 'http://twitter.com/search?q=%23KremlinAnnex'},{ 'name': '#LHHH', 'promoted_content': null, 'query': '%23LHHH', 'tweet_volume': 35252, 'url': 'http://twitter.com/search?q=%23LHHH'}]trends = sorted(trends,key = lambda e:e[’tweet_volume’],reverse = True)

考慮到有些數(shù)據(jù)是NULL,因此需要提前做個處理,對于空的tweet_volume設(shè)置為0,完整代碼:

for item in trends: if(item.get(’tweet_volume’) is None): item[’tweet_volume’] = 0 trends = sorted(trends,key = lambda e:.get(’tweet_volume’) ,reverse = True)

建議用get方式獲取,空值或數(shù)據(jù)不存在這樣不會報錯。

在Python文檔中看到一種性能更高的方法

通過使用 operator 模塊的 itemgetter 函數(shù),可以非常容易的排序這樣的數(shù)據(jù)結(jié)構(gòu)

因此上面的程序可以改寫成

from operator import itemgetterfor item in trends: if(item.get(’tweet_volume’) is None): item[’tweet_volume’] = 0trends = sorted(trends,key = itemgetter(’tweet_volume’),reverse = True)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 欧美一区二区三区在线观看免费 | 日韩欧美亚洲国产一区二区三区 | 成人精品国产亚洲 | 黄色影院免费观看 | 免费看啪啪网站 | 免费高清性色生活片 | 在线视频91| 九九热在线视频免费观看 | 丝袜美足国产一区在线 | 色久在线| 久久精品色 | 色在线看 | 一级裸片 | 亚洲精品一二三 | 99精品久久秒播无毒不卡 | 91区国产 | 98国产精品永久在线观看 | 久热这里只精品99re8久 | 免费观看欧美精品成人毛片能看的 | 国精品产 | 国产中文99视频在线观看 | 女人被狂躁视频免费网站 | 91在线国内在线播放老师 | 性视频一区二区三区免费 | 好色影院 | 久久久精彩视频 | 国产a毛片清高视频 | 在线播放国产不卡免费视频 | 精品在线一区二区 | 国产精品嫩草影院99av视频 | 亚洲欧美中文日韩综合 | 91大神大战丝袜美女在线观看 | 国产精品真实对白精彩久久 | 亚洲 欧美 日韩 综合 | 中国国产一级毛片 | 青草久久精品亚洲综合专区 | 免费播放国产性色生活片 | a毛片在线免费观看 | 亚洲国产日韩欧美高清片a 亚洲国产日韩欧美一区二区三区 | japanhdfree日本护士乱 | 日韩精品久久久毛片一区二区 |