微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我的订购词典无法正常运行

如何解决我的订购词典无法正常运行

所以基本上我有以下代码

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时,它可以正常工作。

关于这种情况为什么发生以及如何解决的任何想法?

解决方法

key_tall = max(person.keys())
key_short = min(person.keys())

您的是整数0..9,因此,由于您要查询的是这两个值,因此您期望分别获得90最小/最大键,而与值无关。

似乎要紧随拥有最高/最低价值的人的钥匙,但这不是该代码所提供的。

如果您追随具有最大值的项目的索引,则可以执行以下操作:

indexes_tall = [idx for idx in range(len(person)) if person[idx] == max(person.keys())]

这将为您提供与最大值匹配的索引列表,然后您可以根据需要对其进行处理。举一个例子:

from collections import OrderedDict as OD
person = OD({})

for num in range(10):
    person[num] = float((num + 1) % 10) # effectively your input

tall = max(person.values())
short = min(person.values())

keys_tall = [str(idx + 1) for idx in range(len(person)) if person[idx] == max(person.keys())]
keys_short = [str(idx + 1) for idx in range(len(person)) if person[idx] == min(person.keys())]

print(f'The shortest height of {short}m is held by: {" ".join(keys_short)}')
print(f'The tallest height of {tall}m is held by: {" ".join(keys_tall)}')

会给您:

The shortest height of 0.0m is held by: 10
The tallest height of 9.0m is held by: 9

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。