Using Python's max to return two equally large values

前端 未结 6 1879
小鲜肉
小鲜肉 2020-11-30 13:29

I\'m using Python\'s max function to find the largest integer in a dictionary called count, and the corresponding key (not quite sure if I\'m saying it properly

6条回答
  •  一个人的身影
    2020-11-30 14:30

    Fast single pass:

    a = { 'a': 120, 'b': 120, 'c': 100 }
    z = [0]
    while a:
        key, value = a.popitem()
        if value > z[0]:
            z = [value,[key]]
        elif value == z[0]:
            z[1].append(key)
    
    print z
    #output:
    [120, ['a', 'b']]
    

    And an amusing way with defaultdict:

    import collections
    b = collections.defaultdict(list)
    for key, value in a.iteritems():
        b[value].append(key)
    print max(b.items())
    #output:
    (120, ['a', 'b'])
    

提交回复
热议问题