国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

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

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

瀏覽:5日期: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 編程
相關文章:
主站蜘蛛池模板: 国产成人高清精品免费5388密 | 亚洲一二区 | 日韩国产三级 | 国产成人最新毛片基地 | 99在线精品免费视频九九视 | 久久国产网 | 自拍偷拍二区 | 亚洲午夜久久久久国产 | 国产深夜福利视频网站在线观看 | 亚洲一区二区三区首页 | 久草国产在线播放 | 国产在线一区二区三区欧美 | 人人操美女 | 韩国精品欧美一区二区三区 | 日韩一区二区三区四区不卡 | 特级无码a级毛片特黄 | 日韩精品另类天天更新影院 | 国产男女视频 | 韩国免费特一级毛片 | 国产一级在线观看www色 | 亚洲国产欧美日韩第一香蕉 | 完整日本特级毛片 | 思思91精品国产综合在线 | 国产毛片一级国语版 | 日本精品一区二区三区在线视频一 | 国产精品看片 | 黄色在线不卡 | 在线观看香蕉免费啪在线观看 | 国产成人影院在线观看 | 激情一区二区三区成人 | 91久久线看在观草草青青 | 免费看一片 | 亚洲午夜精品在线 | 亚洲国产日韩综合久久精品 | 欧美一级片免费在线观看 | 99久久精品国产免看国产一区 | 国产一区免费观看 | 亚洲天堂视频在线观看免费 | 国产成人精品一区二区三在线观看 | 美女视频黄的免费看网站 | 亚洲欧洲日产v特级毛片 |