Using Python's max to return two equally large values

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

提交回复
热议问题