3

我有这本字典,其中(key1,key2):值

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 但我不知道如何。

4

2 回答 2

4

不要调用它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)
于 2012-04-14T04:19:13.757 回答
0
# Use NumPy. It seems this will help if you'll be needing argmin type functions.
# This is BY NO MEANS the only way to do it in Python, but it is a good way to
# know nonetheless.
import numpy as np

my_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'}

# Get the keys
dict_keys = my_dict.keys()

# Get the average value of each key pair.
averages_for_keys = np.array([np.mean(elem) for elem in dict_keys])

# Get the index and the key pair of the largest average.
largest_average_key = dict_keys[averages_for_keys.argmax()]

# Get user input
key1 = input('enter value of key1: ')
key2 = input('enter value of key2: ')

# If not in dict_keys, print for largest average key pair.
if (key1, key2) not in dict_keys:
    print "Invalid input key pair. Proceeding with largest average."
    print my_dict[largest_average_key]


###
# An alternative to index on the closest key by Euclidean distance.
# This can be adjusted for other distances as well.
###
if (key1, key2) not in dict_keys:
    print "Didn't find key pair in dict."
    print "Proceeding with keypair of minimal distance to input."

    dists = np.array([sqrt((elem[0]-key1)**2.0 + (elem[1]-key2)**2.0) for elem in dict_keys])
    min_index = dists.argmin()
    closest_key = dict_keys[min_index]

print my_dict[closest_key]
于 2012-04-14T04:25:05.773 回答