国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-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)文章:
主站蜘蛛池模板: 美女一级视频 | 国产精品自拍亚洲 | 精品国产欧美另类一区 | 日本一级特黄aa毛片免费观看 | 国产主播第一页 | 久色tv| 精品热99| 女人张开腿男人捅 | 亚洲成网站 | 美女擦逼| 久久99久久精品久久久久久 | 特级黄色毛片在放 | 久久tv免费国产高清 | 日本三级香港三级妇三 | 欧美久久一区二区 | 99久久精品免费观看国产 | 国产自产v一区二区三区c | a一区二区三区视频 | 全部免费的毛片视频观看 | 成人久久18免费软件 | 午夜大片免费男女爽爽影院久久 | 狠狠色噜狠狠狠狠色综合久 | 欧美亚洲在线观看 | 成人看的一级毛片 | 中文国产日韩欧美视频 | 亚洲一级成人 | 国产精品久久久久久久久久久威 | 美国一级毛片片aa成人 | 亚州三级视频 | 国产精品亚洲一区二区在线观看 | 国产视频一区二区三区四区 | 最新版天堂资源中文官网 | 亚洲天堂免费视频 | 亚洲高清视频网站 | 日韩中文在线观看 | 日韩久久网 | a男人的天堂久久a毛片 | 99久久免费精品 | 黄色网址免费在线 | 精品呦女 | 久久草在线精品 |