【发布时间】:2021-01-01 05:06:06
【问题描述】:
所以基本上我有这个代码:
from collections import OrderedDict as OD
person = OD({})
for num in range(10):
person[num] = float(input())
tall = max(person.values())
short = min(person.values())
key_tall = max(person.keys())
key_short = min(person.keys())
print(f'The shortest person is the person number {key_short} who is {short}meters tall')
print(f'The tallest person is the person number {key_tall} who is {tall}meters tall')
理论上,当我在字典中放 10 个人时,第一个数字是 1,一直到 9,最后一个数字是 0,输出应该是:
The shortest person is the person number 9 who is 0.0m meters tall
The tallest person is the person number 8 who is 9.0m meters tall
但实际上它会打印:
The shortest person is the person number 0 who is 0.0m meters tall
The tallest person is the person number 9 who is 9.0m meters tall
由于某种原因,当我的字典的值从 1 一直到 10 时,它工作正常。
关于为什么会发生这种情况以及如何解决它的任何想法?
【问题讨论】:
-
max(person.keys())会给你最大键,而不是最大值的人的键。与min相同。请注意,您使用OrderedDict是否有任何特殊原因?
标签: python dictionary collections ordereddict