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

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

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

瀏覽:17日期: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ù)以字典的方式獲取,相當于把取出的就是后面的列表,即

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)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 久草网在线视频 | 黄黄视频在线观看 | 国产成人精品18 | 欧美精品亚洲精品日韩经典 | 18欧美乱大交hd88av | 色男人的天堂久久综合 | 日韩 国产 欧美 精品 在线 | 色综合亚洲综合网站综合色 | 热久久最新地址 | 久久观看| 国模私拍高清大胆专业网站 | 成年黄色| 97视频免费公开成人福利 | 成人18网址在线观看 | 一级片a| 国产成人18黄网站麻豆 | 日韩在线不卡 | 日本不卡在线一区二区三区视频 | xxxx久久| 欧美日日操| 久久久久久久久女黄9999 | 成人国产一区二区三区精品 | 久久国产精品自由自在 | 国产a三级三级三级 | 欧美αv日韩αv亚洲αv在线观看 | 成人性色大片 | 麻豆短视频传媒网站怎么找 | 日韩激情中文字幕一区二区 | 7788成年网站免费观看 | v天堂一卡2卡三卡4卡乱码 | 韩国 欧美 日产 国产精品 | 国产精品综合一区二区 | 国产一国产一级毛片视频 | 日本不卡中文字幕一区二区 | 免费观看国产 | 免费视频不卡一区二区三区 | 国产精品新婚门 | 日本不卡视频一区二区三区 | 中国大陆一级毛片 免费 | 在线观看永久免费视频网站 | 国产免费播放一区二区三区 |