Python实现对嵌套列表字典按某一元素合并及lambda的使用
2016-01-12 09:38
1111 查看
#! /usr/bin/env python #coding=utf-8 class MergeResource(object): def __init__(self, resource_list): self.resource_list = resource_list def merge_resource(self): merge_resource = [] merge_resource.append(self.resource_list[0])#加入第一个 for dict in self.resource_list[1:]: #把第一个排除 k=0 for item in merge_resource: if dict['host'] == item['host']: item['cpu'] += dict['cpu'] item['mem'] += dict['mem'] break else: k=k+1 if k == len(merge_resource): merge_resource.append(dict) break #不加就会有错误!!! #print 'merge_resource: ', merge_resource return merge_resource if __name__ == '__main__': resource_list=[{'host':'compute21', 'cpu':2, 'mem':4},{'host':'compute21', 'cpu':2, 'mem':4}, {'host':'compute22', 'cpu':2, 'mem':4},{'host':'compute23', 'cpu':2, 'mem':4}, {'host':'compute22', 'cpu':2, 'mem':4},{'host':'compute23', 'cpu':2, 'mem':4}, {'host':'compute24', 'cpu':2, 'mem':4}] #1、merge之前 maxResourceHost = max(resource_list, key = lambda x: x['cpu'])['host'] print 'maxResourceHost: ', maxResourceHost maxResourceCpu = max(resource_list, key = lambda x: x['cpu'])['cpu'] print 'maxResourceCpu: ', maxResourceCpu #1、merge之后 merge = MergeResource(resource_list) merge_resource = merge.merge_resource() print 'merge_resource: ' print merge_resource maxResource = max(merge_resource, key = lambda x: x['cpu']) print 'maxResource: ', maxResource maxResourceCpu = max(merge_resource, key = lambda x: x['cpu'])['cpu'] print 'maxResourceCpu: ', maxResourceCpu
结果:
maxResourceHost: compute21 maxResourceCpu: 2 merge_resource: [{'mem': 8, 'host': 'compute21', 'cpu': 4}, {'mem': 8, 'host': 'compute22', 'cpu': 4}, {'mem': 8, 'host': 'compute23', 'cpu': 4}, {'mem': 4, 'host': 'compute24', 'cpu': 2}] maxResource: {'mem': 8, 'host': 'compute21', 'cpu': 4} maxResourceCpu: 4
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法