午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

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

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

瀏覽:4日期: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 編程
相關文章:
主站蜘蛛池模板: 久久久婷婷 | 久久99国产综合精品免费 | 中文字幕av一区二区三区 | 久久网站视频 | 国内偷拍久久 | 伊人网综合视频 | 9色在线视频 | 黄色小视频在线免费看 | 在线播放黄色网址 | 伊人狼人久久 | 亚洲一区在线观看视频 | 久热在线视频 | 男人操女人的视频网站 | 免费午夜影院 | 日韩在线毛片 | 国产黄色大片网站 | 久久久久久成人 | 亚洲黄色成人 | 九九九在线 | 最新中文字幕在线视频 | 97国产超碰 | 欧美黑人一区二区三区 | 色av一区| 一级成人毛片 | 操极品美女| 天堂在线一区二区 | av一区二区三区 | 国产精品一区二区在线播放 | 国产黄a三级三级三级看三级男男 | 一区二区三区三区在线 | 视频福利在线 | 国产色视频在线 | 国产黄色在线看 | 久久久久久久久久免费 | 亚洲天堂2016| 中文av一区| 天堂中文在线资 | 欧美激情性做爰免费视频 | 99在线视频观看 | 久久久综合久久久 | 黄色片网站在线播放 |