返回一个列表中出现次数最多的元素


def zuiduo_yuansu():
    a=list(input('请输入任意个元素:'))
    print(max(a,key=a.count))
zuiduo_yuansu()
lt = ['李白', '李商隐', '李贺', '李清照', '李煜', '李杰', '杜甫', '杜牧', '白居易', '李白', '李清照', '岳飞', '李白']

def max_word(lt):
    # 定义一个字典,用于保存每个元素及出现的次数
    d = {}
    # 记录做大的元素(字典的键)
    max_key = None
    for w in lt:
        if w not in d:
            # 统计该元素在列表中出现的次数
            count = lt.count(w)
            # 以元素作为键,次数作为值,保存到字典中
            d[w] = count
            # 记录最大元素
            if d.get(max_key, 0) < count:
                max_key = w
    return max_key

print(max_word(lt))
---------------------

猜你喜欢

转载自blog.csdn.net/YZXnuaa/article/details/89398035