Python实现对嵌套列表字典按某一元素合并及lambda的使用
来源:互联网 发布:js获取unix时间戳 编辑:程序博客网 时间:2024/06/13 04:53
#! /usr/bin/env python#coding=utf-8class 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_resourceif __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: compute21maxResourceCpu: 2merge_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
0 0
- Python实现对嵌套列表字典按某一元素合并及lambda的使用
- python实现嵌套列表、字典按某一元素去重复
- Python使用collections的Counter类对字符串、列表、字典的数据元素进行计数
- python 一个单列表和一个字典元素的列表合并
- python 中字典嵌套列表
- Python 函数字典列表嵌套
- Python 嵌套列表的排序(匿名函数lambda)
- python列表、元组、字典的元素空格去除,及转换资料
- Python列表,元祖及字典的区别
- Python列表序列及字典的操作
- Python sorted 对字典列表
- Python 字典 列表 嵌套 复杂排序大全
- python字典和列表各种嵌套排序
- Python--两个列表合并成字典
- Python:将一维列表的元素合并为一个字符串
- 使用python字典合并文本
- python 中字典{ }的嵌套
- python 嵌套字典的定义
- jquery,bootstrap实现的用户名片信息提示
- <iOS>AFNetworking 3.0的使用
- String字符串判断是否一致要注意的问题
- COCOS学习笔记--精灵Sprite的3种创建方法总结
- ansj_seg
- Python实现对嵌套列表字典按某一元素合并及lambda的使用
- tomcat xml配置文件部署项目
- 浅谈响应式布局
- tcp_nodelay(1)
- 公开密匙(public key)和专用密匙(private key)
- Java多线程用法解析
- Android退出应用的几种方式
- Tomcat上运行正常,部署在weblogic服务器上,不认jsp等标签问题
- iptables的五个关口