Python實現(xiàn)嵌套列表及字典并按某一元素去重復(fù)功能示例
本文實例講述了Python實現(xiàn)嵌套列表及字典并按某一元素去重復(fù)功能。分享給大家供大家參考,具體如下:
#! /usr/bin/env python #coding=utf-8 class HostScheduler(object): def __init__(self, resource_list): self.resource_list = resource_list def MergeHost(self): allResource=[] allResource.append(self.resource_list[0]) for dict in self.resource_list: #print len(l4) k=0 for item in allResource: #print 'item' if dict['host'] != item['host']: k=k+1 #continue else: break if k == len(allResource): allResource.append(dict) taskhost=[] for item in allResource: taskhost.append(item['host']) return taskhost #該函數(shù)實現(xiàn)嵌套列表中,按某一元素去重復(fù) def deleteRepeat(): #1、列表中嵌套列表。按元素‘b'實現(xiàn)去重復(fù) l1=[['b',1],['b',2],['c',3],['a',1],['b',1],['b',1],] l2=[] l2.append(l1[0]) for data in l1: #print len(l2) k=0 for item in l2: #print 'item' if data[0] != item[0]: k=k+1 else: break if k == len(l2): l2.append(data) print "l2: ",l2 #2、列表中嵌套字典。按鍵值host實現(xiàn)去重復(fù) l3=[{'host':'compute21', 'cpu':2},{'host':'compute21', 'cpu':2},{'host':'compute22', 'cpu':2}, {'host':'compute23', 'cpu':2},{'host':'compute22', 'cpu':2},{'host':'compute23', 'cpu':2}, {'host':'compute24', 'cpu':2}] l4=[] l4.append(l3[0]) for dict in l3: #print len(l4) k=0 for item in l4: #print 'item' if dict['host'] != item['host']: k=k+1 #continue else: break if k == len(l4): l4.append(dict) print "l4: ",l4 if __name__ == '__main__': #deleteRepeat() resource_list=[{'host':'compute21', 'cpu':2},{'host':'compute21', 'cpu':2},{'host':'compute22', 'cpu':2}, {'host':'compute23', 'cpu':2},{'host':'compute22', 'cpu':2},{'host':'compute23', 'cpu':2}, {'host':'compute24', 'cpu':2}] hostSchedule=HostScheduler(resource_list) taskhost=hostSchedule.MergeHost() print '腳本之家測試結(jié)果: ' print 'taskhost: ' print taskhost
運行結(jié)果:
PS:本站還有兩款比較簡單實用的在線文本去重復(fù)工具,推薦給大家使用:
在線去除重復(fù)項工具:
http://tools.jb51.net/code/quchong
在線文本去重復(fù)工具:
http://tools.jb51.net/aideddesign/txt_quchong
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python字典操作技巧匯總》、《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python采集天天基金數(shù)據(jù)掌握最新基金動向
這篇文章主要介紹了Python采集天天基金數(shù)據(jù)掌握最新基金動向,本次案例實現(xiàn)流程為發(fā)送請求、獲取數(shù)據(jù)、解析數(shù)據(jù)、多頁爬取、保存數(shù)據(jù),接下來來看看具體的操作過程吧2022-01-01用python生成(動態(tài)彩色)二維碼的方法(使用myqr庫實現(xiàn))
今天小編就為大家分享一篇用python生成(動態(tài)彩色)二維碼的方法(使用myqr庫實現(xiàn)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06