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

您的位置:首頁技術文章
文章詳情頁

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

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

在做項目的時候,遇到這樣的數據:

'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'}]

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

實現代碼:

把上面數據以字典的方式獲取,相當于把取出的就是后面的列表,即

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)

考慮到有些數據是NULL,因此需要提前做個處理,對于空的tweet_volume設置為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方式獲取,空值或數據不存在這樣不會報錯。

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

通過使用 operator 模塊的 itemgetter 函數,可以非常容易的排序這樣的數據結構

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

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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 亚洲综合激情另类专区 | 国产大战女模特在线视频 | 欧洲一级做a爱在线观看 | 黄色影 | 亚洲免费人成在线视频观看 | 午夜成年人视频 | 精品日韩二区三区精品视频 | 免费看一级特黄a大片 | 国产精品一级二级三级 | 2020国产精品自拍 | 亚洲看| 外国黄色网| 国产高清厕所盗摄视频 | 亚洲另类在线观看 | 91热爆国产露脸 | 国产福利专区 | 中文字幕在线观看第一页 | 九九热在线视频免费观看 | 亚洲精品乱码久久久久久 | 亚洲精品一区二区三区在线播放 | 在线免费观看国产视频 | 丰满的日本护士xxx 丰满美女福利视频在线播放 | 日韩免费不卡视频 | 精品国产免费人成网站 | 亚洲国产九九精品一区二区 | 欧美精品亚洲精品日韩专 | 亚洲在线影院 | 国产91po在线观看免费观看 | 色偷偷女男人的天堂亚洲网 | 久久ri精品高清一区二区三区 | 免费的污污网站 | 中文精品久久久久国产不卡 | 欧美ol丝袜高跟秘书在线播放 | 香蕉视频在线观看网站 | 国产特级毛片aaaaaa | 99je全部都是精品视频在线 | 在线日韩麻豆一区 | 免费视频一区二区性色 | 国产又黄又爽又色视频影视网免费 | 国产精品亚洲欧美 | 三级三级三级网站网址 |