python - 实现列表,字典嵌套去重(key去重,value去重)
2017-12-06 23:46
961 查看
摘自:http://m.blog.csdn.net/will130/article/details/50441937
输出结果:
t1 = [{'a':1}, {'a':2}, {'a':2}] #dict([d.items()[0] for d in t1]).items()之外的部分纯粹是把列表内还原成一个字典 t2 = [{value:key} for key, value in dict([d.items()[0] for d in t1]).items()]
#! /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 #该函数实现嵌套列表中,按某一元素去重复 def deleteRepeat(): #1、列表中嵌套列表。按元素‘b’实现去重复 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实现去重复 l3=[{'host':'co b2bc mpute21', '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 'taskhost: ' print taskhost
输出结果:
l2: [['b', 1], ['c', 3], ['a', 1]] l4: [{'host': 'compute21', 'cpu': 2}, {'host': 'compute22', 'cpu': 2}, {'host': 'compute23', 'cpu': 2}, {'host': 'compute24', 'cpu': 2}] taskhost: ['compute21', 'compute22', 'compute23', 'compute24']
相关文章推荐
- Python实现嵌套列表及字典并按某一元素去重复功能示例
- 无限遍历,python实现在多维嵌套字典、列表、元组的JSON中获取数据
- python字典嵌套字典的情况下获取某个key的value
- python实现字典按value排序,以及按照key排序的实现方法
- 无限遍历,Python实现在多维嵌套字典、列表、元组的JSON中获取数据
- [置顶] 无限遍历,python实现在多维嵌套字典、列表、元组的JSON中获取数据
- Python实现对嵌套列表字典按某一元素合并及lambda的使用
- 用字典推导式实现字典key和value的交换--python小技巧
- python中获取字典的key列表和value列表
- python实现嵌套列表、字典按某一元素去重复
- Python 列表实现字典的get功能
- python字典value为列表时遇到的问题
- python 实现将字典dict、列表list中的中文正常显示方法
- python 按字典value排序以及按list中字典的某个key的value排序
- 实现向 python 脚本中传递列表,字典参数
- python 中字典嵌套列表的方法
- Python从单元素字典中获取key和value
- 列表里面有字典[{},{},{},{}],按着字典的指定的key所对应的value值得大小排序
- python提取字典key列表的方法
- python 合并字典,相同 key 的 value 如何相加?