色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

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

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

瀏覽:7日期: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 編程
相關文章:
主站蜘蛛池模板: 欧美激情视频在线观看一区二区三区 | av在线手机播放 | 国产一级毛片外aaaa | 国产永久免费高清动作片www | 免费一级大毛片a一观看不卡 | 成人二区| 欧美一级特黄特色大片 | 久久一本综合 | 久久精品视频1 | 欧美视频自拍偷拍 | 天天鲁天天爱天天鲁天天 | 亚洲久草视频 | 欧美亚洲一区二区三区在线 | 久久国产经典视频 | 欧美同性videos在线可播放 | 免费一级片视频 | chinese宾馆自拍hd | 欧美特黄一级 | 美国一级毛片oo | 成人三级精品视频在线观看 | 另类专区 亚洲 | 情侣偷偷看的羞羞视频网站 | 欧美精品久久天天躁 | 亚洲高清中文字幕一区二区三区 | www夜色| 成人欧美一区二区三区 | 手机看片精品高清国产日韩 | 亚洲一级毛片免费看 | 日韩经典欧美精品一区 | 女人夜色黄网在线观看 | 成年人黄色免费网站 | 成年男人的天堂 | 日韩不卡一二三区 | 国产精品亚洲精品影院 | 亚洲国产精品久久久久久网站 | a级毛片毛片免费很很综合 a级毛片免费 | 欧美片欧美日韩国产综合片 | 亚洲精品免费观看 | 在线观看亚洲网站 | 久草在线免费看 | 国产99视频精品免费观看9e |