Using Python's max to return two equally large values

前端 未结 6 1854
小鲜肉
小鲜肉 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:14

    To print a list without bucket. use :

    ' '.join(map(str, mylist))
    

    or, more verbosely:

    ' '.join(str(x) for x in mylist)
    
    0 讨论(0)
  • 2020-11-30 14:17

    Sometimes simplest solution may be the best:

    max_value = 0
    max_keys = []
    
    for k, v in count.items():
        if v >= max_value:
            if v > max_value:
                max_value = v
                max_keys = [k]
            else:
                max_keys.append(k)
    
    print max_keys
    

    The code above is slightly faster than two pass solution like:

    highest = max(count.values())
    print [k for k,v in count.items() if v == highest]
    

    Of course it's longer, but on the other hand it's very clear and easy to read.

    0 讨论(0)
  • 2020-11-30 14:20

    Same idea as Asterisk, but without iterating over the list twice. Bit more verbose.

    count = { 'a': 120, 'b': 120, 'c': 100 }
    answers = []
    highest = -1
    
    def f(x):
        global highest, answers
        if count[x] > highest:
            highest = count[x]
            answers = [x]
        elif count[x] == highest:
            answers.append(x)
    
    map(f, count.keys())
    print answers
    
    0 讨论(0)
  • 2020-11-30 14:27

    This could be a way (probably not the most efficient).

    value = max(count.values())
    filter(lambda key: count[key]==value,count)
    
    0 讨论(0)
  • 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'])
    
    0 讨论(0)
  • 2020-11-30 14:33

    Idea is to find max value and get all keys corresponding to that value:

    count = {'a': 120, 'b': 120, 'c': 100}
    
    highest = max(count.values())
    
    print([k for k, v in count.items() if v == highest])
    
    0 讨论(0)
提交回复
热议问题