我的要求是收集设备对象(具有容量,制造商,带宽,成本等作为功能)。我需要能够找到具有最大容量的设备。但由于可能存在来自相同或不同制造商的具有相同容量的多个设备,因此我无法使用容量作为密钥。
我想过将容量和型号的元组作为关键但是我根据容量选择设备而不是他们的型号。
class device:
def __init__(self):
self.manufacturer = ""
self.purchasecost = ""
self.capacity = "" # TB
self.power = "" # KWH
self.bandwidth = "" # MBPS
self.fail_rate = ""
self.powered_on = "" # %
self.lIOPS = ""
self.device_type = ""
self.moveincost = "" # % of purchasecost
self.moveoutcost = "" # % of purchasecost
self.datacentercost = ""
self.servicelife = ""
self.model = ""
pass
def setparam(self, device_param):
self.manufacturer = device_param["manufacturer"]
self.purchasecost = device_param["purchasecost"]
self.capacity = device_param["capacity"] # TB
self.power = device_param["power"] # KWH
self.bandwidth = device_param["bandwidth"] # MBPS
self.fail_rate = device_param["fail_rate"]
self.powered_on = device_param["powered_on"] # %
self.lIOPS = device_param["IOPS"]
self.device_type = device_param["device_type"]
self.moveincost = device_param["moveincost"] # % of purchasecost
self.moveoutcost = device_param["moveoutcost"] # % of purchasecost
self.datacentercost = device_param["datacentercost"]
self.servicelife = device_param["servicelife"]
self.model = device_param["model"]
在另一个类中,我正在创建对象并使用它们。
def available_devices(self):
hdd1 = self.createdisk1()
hdd2 = self.createdisk2()
ssd1 = self.createSSD1()
self.availabledevices[hdd1.model]=hdd1
print ( "Added HDD1 "+str(self.availabledevices[hdd1.model]))
self.availabledevices[hdd2.model]=hdd2
print ( "Added HDD2 "+str(self.availabledevices[hdd2.model]))
self.availabledevices[ssd1.model]=ssd1
def get_highest_capacity_device(self):
sorted_capacities = sorted(self.availabledevices.iterkeys())
highest_capacity = sorted_capacities[len(sorted_capacities) -1]
highest_capacity_device = self.availabledevices[highest_capacity]
return highest_capacity_device
此代码目前使用容量作为密钥,但是当有多个具有相同容量的设备时,它显然不起作用。我的问题是我应该使用什么作为关键所以 - 我可以根据他们的容量对我的设备进行排序 - 我可以让所有设备都具有一定的容量
答案 0 :(得分:3)
为什么你还要使用字典呢?与简单列表相比没有任何好处:
availabledevices = [ hdd1, hdd2, ssd ]
highest_capacity_device = max(availabledevices, key=lambda x: x.capacity)