Python實(shí)現(xiàn)嵌套列表及字典并按某一元素去重復(fù)功能示例
本文實(shí)例講述了Python實(shí)現(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ù)實(shí)現(xiàn)嵌套列表中,按某一元素去重復(fù)
def deleteRepeat():
#1、列表中嵌套列表。按元素‘b'實(shí)現(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實(shí)現(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 '腳本之家測(cè)試結(jié)果: '
print 'taskhost: '
print taskhost
運(yùn)行結(jié)果:

PS:本站還有兩款比較簡(jiǎn)單實(shí)用的在線文本去重復(fù)工具,推薦給大家使用:
在線去除重復(fù)項(xiàng)工具:
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ìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
Python采集天天基金數(shù)據(jù)掌握最新基金動(dòng)向
這篇文章主要介紹了Python采集天天基金數(shù)據(jù)掌握最新基金動(dòng)向,本次案例實(shí)現(xiàn)流程為發(fā)送請(qǐng)求、獲取數(shù)據(jù)、解析數(shù)據(jù)、多頁爬取、保存數(shù)據(jù),接下來來看看具體的操作過程吧2022-01-01
Python Web日志管理與監(jiān)控實(shí)踐指南
這篇文章主要介紹了Python Web日志管理與監(jiān)控實(shí)踐指南,文中通過代碼示例講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-09-09
用python生成(動(dòng)態(tài)彩色)二維碼的方法(使用myqr庫實(shí)現(xiàn))
今天小編就為大家分享一篇用python生成(動(dòng)態(tài)彩色)二維碼的方法(使用myqr庫實(shí)現(xiàn)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06

