【问题标题】:List as value in dictionary, get key of longest list列表作为字典中的值,获取最长列表的键
【发布时间】:2013-11-07 19:48:37
【问题描述】:

给一本这样的字典

testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59]}

如何获取最长列表的键?在这种情况下,它将是32

【问题讨论】:

  • 如果有多个键的关联值具有最大长度,您希望发生什么?
  • 好问题。那么我想获得多个密钥。

标签: python list dictionary


【解决方案1】:

使用max:

>>> max(testDict, key=lambda x:len(testDict[x]))
32

如果多个键包含最长的列表:

那我想获取多个密钥。

>>> testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59], 10: [1, 2, 3, 4]}
>>> mx = max(len(x) for x in testDict.itervalues())
>>> [k for k, v in testDict.iteritems() if len(v)==mx]
[32, 10]

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多