Illinois: ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3']
Indiana: ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2']
这些在我的字典中是 d。 如何获取字典中每个键的最大和最小值,并获取该值所在的索引。
例如: 在伊利诺伊州,26 是最大值,即索引 5,3 是最小值,即索引 15。 在印第安纳州:13 是最大值,即索引 7,2 是最小值,即索引 14
输出:
Illinois: 26 in index 5 and 3 in index 15
Indiana: 13 in index 7 and 2 in index 14
我该怎么做?
d = {}
for row in csv_f:
d[row[0]]=row[1:]
最佳答案
您可以打印出最大值和分钟,因为您的字符串如下所示:
(假设您只想要第一次出现)
MY_D = {'Illinois': ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3'],
'Indiana': ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2']}
for k,v in MY_D.items():
#This assumes that everything in v is an int, or rather can be converted to one.
my_l = [int(n) for n in v]
#if not
#my_l = [int(n) for n in v if n.isdigit()]
_max, _min = max(my_l), min(my_l)
print("%s: Min - %d in index %d, Max - %d in index %d" % (k, _min, my_l.index(_min), _max, my_l.index(_max)))
关于python - 获取字典中的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585003/