【问题标题】:How to iterate over a dictionary and find the max values python?如何遍历字典并找到最大值python?
【发布时间】:2016-02-17 15:37:28
【问题描述】:

我有一本这样的字典:

aDict = {'a': [1,2,3],
         'b': [2,3,4],
         'c': [3,3,6], ...}

如何创建一个列表来存储每个索引 (0,1,2) 处的最大值。 谢谢!

【问题讨论】:

  • 您希望结果是什么样的?
  • [max(integers) for integers in aDict.values()] == [3, 4, 6]
  • 什么是索引(0, 1, 2)?字典没有索引,只有键。在这种情况下{'a', 'b', 'c'}

标签: python dictionary


【解决方案1】:

如果我理解正确,你想要这样的东西:

>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aList = [max(aDict[k]) for k in sorted(aDict.keys())]
>>> print aList
[3, 4, 6]

或者这样:

>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aDict2 = dict((k, max(aDict[k])) for k in aDict.keys())
>>> print aDict2
{'a': 3, 'c': 6, 'b': 4}

【讨论】:

  • 在后者中,您可以使用字典理解{k: max(v) for k, v in aDict.iteritems()}(如果python 3,将.iteritems替换为.items)。
猜你喜欢
  • 2020-04-02
  • 2015-09-27
  • 1970-01-01
  • 2011-01-16
  • 2019-05-29
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多