#! /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