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

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

Python按照l(shuí)ist dict key進(jìn)行排序過程解析

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

在做項(xiàng)目的時(shí)候,遇到這樣的數(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ù)值對(duì)trends里的元素進(jìn)行排序。

實(shí)現(xiàn)代碼:

把上面數(shù)據(jù)以字典的方式獲取,相當(dāng)于把取出的就是后面的列表,即

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,因此需要提前做個(gè)處理,對(duì)于空的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ù)不存在這樣不會(huì)報(bào)錯(cuò)。

在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)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 国产东北色老头老太性视频 | 欧美成人免费夜夜黄啪啪 | 亚洲一区二区视频 | 欧美亚洲综合网 | 亚洲精品国产精品精 | 真人一级一级特黄高清毛片 | 国产亚洲精品成人a在线 | 国内精品国语自产拍在线观看55 | 欧美a一级片 | 欧美高清一区二区三区欧美 | 99在线观看巨臀大臀视频 | 91手机看片国产福利精品 | 高h原耽肉汁动漫视频 | 亚洲日本在线看片 | 成人欧美一区二区三区 | 97成人在线视频 | 日本欧美视频 | 国产真实生活伦对白 | 三级视频网站在线观看播放 | 国产在线观看成人 | 国产大臿蕉香蕉大视频 | 久久久久久91香蕉国产 | 男人天堂男人天堂 | xxxwww黄色| 亚洲无色| 久久精品成人欧美大片免费 | 中国内地毛片免费高清 | 欧美一级aⅴ毛片 | 欧美另类videosbestsex视频 | 国产91久久精品一区二区 | 韩国精品视频在线观看 | 亚洲综合第一欧美日韩中文 | 亚洲高清自拍 | 99精品免费 | 成年人在线免费观看网站 | 在线播放国产视频 | 高清一区二区三区四区五区 | 黄色网址网站在线观看 | 国产在线观看免费人成小说 | 777色狠狠一区二区三区 | 男女男在线精品网站免费观看 |