我有类似的字典:
table_wood = {'Red': {'Abbreviation': 'R',
'Instances': 269601,
'Code': '8924',
'Discovered': '1876-08-01',
'Largest usage': 'Douglas',
'Indigo': {'Abbreviation': 'IN',
'Instances': 216443,
'Code': '2343',
'Discovered': '1890-07-03',
'Largest usage': 'Freida'}}
我需要遍历table_wood字典并为table_wood中的每个字典计算(实例/代码)。完成此操作后,我需要报告实例数量最多,实例数量最少的
。我尝试使用for循环将相关值附加到空列表,然后使用嵌套的for循环比较这些列表值,以查看哪个原始实例最大和最小。 它涉及大量的空列表,我知道,如果可以将它们作为新的键/值对存储在空字典中,这是一种更好的方法。
instanceCodeRate = []
colorInstances = []
highestInstance = []
lowestInstance = []
for color in table_wood:
colorRate.append(color+ ": " +str(round((table_wood[color]["Instances"])/(table_wood[color]["Code"]),2))+ " instances per code.\n")
#print(instanceCodeRate)
colorInstances.append(table_wood[color]["Instances"])
#print(colorInstances)
for instance in colorInstances:
if ((table_wood[color]["Instances"]) == min(colorInstances)):
lowestInstance.append(color)
elif ((table_wood[color]["Instances"]) == max(colorInstances)):
highestInstance.append(color)
#print(instanceCodeRate)
#print(highestInstance)
#print(lowestInstance)
当我打印(instanceCodeRate)时,它作为列表元素来执行,这使我要打印的“ \ n”空白字符无效,因此每个条目都有自己的行。 我的elif只能存储最大的列表,但是由于某种原因,存储最小的if语句可以存储多个列表元素,而应该只有一个。
答案 0 :(得分:0)
Python的max
函数接受一个可选的key
参数
colors = list(table_wood.keys())
attrs = list(table_wood.values())
max_value = max(attrs, key=lambda: x: x['Instances']/int(x['Code']))
打印出来:
{'Abbreviation': 'IN',
'Instances': 216443,
'Code': '2343',
'Discovered': '1890-07-03',
'Largest usage': 'Freida'}
可以使用min