python - 获取字典中的最大值和最小值

标签 python dictionary

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/

相关文章:

python - 对行进行分组并计算平均值和计数

python - 为什么 Tkinter 在打包滚动条时会卡住?

Python:如何获得两个连续分布的卷积?

Python3/MacOSX 集成到 pycharm

c# - 从列表<Control>获取字典<string,string>

java - containsKey 与网址不匹配

javascript - $http angularJS 循环每个带有传单问题的对象

python - 立即转义整个字典/JSON

python - 如果字典键不可用,则返回默认值

python - 为什么我的 Docker 容器在启动后没有将控制权返回给终端?