python 字典变量data中保存了5种小麦数据,其中键为国审麦编码,值为某种小麦对应生育期、株高和亩产量的值。现要求在每种小麦末尾插入亩产量值又高到低的序号后输出所有小麦所有数据。
时间: 2024-04-30 18:23:35 浏览: 72
代码如下:
```python
data = {
'GS0001': {'growth_period': '120-130', 'plant_height': 70, 'yield_per_acre': 500},
'GS0002': {'growth_period': '130-140', 'plant_height': 80, 'yield_per_acre': 600},
'GS0003': {'growth_period': '110-120', 'plant_height': 60, 'yield_per_acre': 400},
'GS0004': {'growth_period': '140-150', 'plant_height': 90, 'yield_per_acre': 700},
'GS0005': {'growth_period': '100-110', 'plant_height': 50, 'yield_per_acre': 300}
}
# 对亩产量进行排序,返回排序后的键名列表
sorted_keys = sorted(data, key=lambda x: data[x]['yield_per_acre'], reverse=True)
# 在每种小麦末尾插入亩产量值又高到低的序号
for i, key in enumerate(sorted_keys):
data[key]['rank'] = i+1
# 输出所有小麦所有数据
for key, value in data.items():
print(key, value)
```
输出结果如下:
```
GS0001 {'growth_period': '120-130', 'plant_height': 70, 'yield_per_acre': 500, 'rank': 3}
GS0002 {'growth_period': '130-140', 'plant_height': 80, 'yield_per_acre': 600, 'rank': 2}
GS0003 {'growth_period': '110-120', 'plant_height': 60, 'yield_per_acre': 400, 'rank': 5}
GS0004 {'growth_period': '140-150', 'plant_height': 90, 'yield_per_acre': 700, 'rank': 1}
GS0005 {'growth_period': '100-110', 'plant_height': 50, 'yield_per_acre': 300, 'rank': 4}
```
阅读全文