python笔试题之找出一个列表里出现频次最高的元素(most common elements in a list)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010870545/article/details/52652706
def most_common(seq):
    d = {}
    for i in seq:
       d[i] = d.get(i, 0) + 1
    ret = []
    for j in sorted(d.items(), reverse=True, key=lambda x:x[1]):
        if len(ret) == 0:
            ret.append(j[0])
            n = j[1]
        else:
            if j[1] == n:
                ret.append(j[0])
            else:
                break
    return ret
print '频次最高', most_common([1,2,3,4,5,1,1,2,2])

猜你喜欢

转载自blog.csdn.net/u010870545/article/details/52652706