gpt4 book ai didi

python - 使用数学函数遍历字典

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:54 24 4
gpt4 key购买 nike

我有这本字典 which in which (key1, key2): value

dict = {('1', '4'): 'A', ('3', '8'): 'B', ('4', '7'): 'C', 
('8', '9'): 'D', ('4', '2'): 'E', ('2', '0'): 'F', ('3', '9'):
'G', ('7', '7'): 'H', ('8', '6'): 'I', ('5', '3'): 'J',
('6', '1'): 'K'}

key1 = input('enter value of key1: ')
key2 = input('enter value of key2: ')

如果我输入一对 key1, key2 并且这对不存在,有没有什么方法可以遍历这个字典并传递一个数学函数,即找到每对键的平均值并打印一个那个有最大的平均值?

编辑:实际上这个字典是从文本文件派生的,所以它必须首先是字符串,我需要将它转换为 int,但我不知道如何。

最佳答案

不要将其命名为 dict,这样会阻止您访问内置的 dict

你的键是strings,所以没有平均值。如果我们转换为 ints:

dct = dict((tuple(map(int, key)), value) for key, value in str_dict.iteritems())

给出:

dct = {(8, 9): 'D', (4, 7): 'C', (6, 1): 'K', (7, 7): 'H', 
(1, 4): 'A', (3, 8): 'B', (2, 0): 'F', (3, 9): 'G',
(4, 2): 'E', (8, 6): 'I', (5, 3): 'J'}

然后你可以使用maxsum 上每个键的:

key = max(d, key=sum)
# (8, 9) is the key with the highest average value

因为sum 最高的那个也有最高的平均值。

如果您随后想要该键的值,则为:

value = dct[key]
# 'D' is the value for (8, 9)

关于python - 使用数学函数遍历字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com