python - 在元组列表中查找多种模式 - python

标签 python tuples mode median

我是 python 的新手,需要一些帮助来找出元组的模式。但是,我现在的代码只显示一种模式,我需要更改什么才能显示多种模式(如果数字列表超过 1 个)

    import itertools
    import operator

    def mode_function2(lst):
       return max(set(lst), key=lst.count)

最佳答案

这个有效:

from collections import Counter
def mode_function2(lst):
    counter = Counter(lst)
    _,val = counter.most_common(1)[0]
    return [x for x,y in counter.items() if y == val]

下面是一个演示:

>>> mode_function2([1, 2, 2])
[2]
>>> mode_function2([1, 2, 2, 1])
[1, 2]
>>> mode_function2([1, 2, 3])
[1, 2, 3]
>>>

这里的重要概念是:

关于python - 在元组列表中查找多种模式 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035448/

相关文章:

python - pydantic:对具有别名的字段使用 property.getter 装饰器

python - 如何在 python 元组中获取不同的元素?

tuples - Kotlin:如何修改成对的值?

spring - Quartz 调度程序未启动。在待机模式

java - 按频率排序字符串数组的最有效方法

python - python中的多进程会重新初始化全局变量吗?

python - Enthought Canopy 中的多个内核

python - 使用 Python 在 Plotly 中的绘图上添加通用文本标签

c++ - 如何用元组转发unique_ptr?

r - 如何在 R 中计算模式但删除 NA 值