python - 如何编写一个找到列表模式并将其保存为字典的函数?

标签 python dictionary

我需要帮助编写一个函数 findMode(aList),该函数接受项目列表作为参数,然后继续查找模式。但是,您的 Python 解决方案必须使用字典来跟踪项目及其计数,作为查找模式的方法(不是平行列表)。

这是我已经尝试过的代码:

def findMode(aList):
    aList.sort()
    position = 0
    largestCount = 0
    listLength = len(aList)
    while(position <= listLength):
        count = aList.count(aList[position])
        if(count > largestCount):
            largestCount = count
            valuePosition = aList[position]
        position += count
    return aList[valuePosition]

以下是预期结果的一些示例:

>>> findMode([4,3,4,3,2,1,4,5,3,3,4,5,1,4,1,4,5])
[4]
>>> findMode(["horse ", "cat ", "dog ", "turtle ","horse ", "cat ", "dog ", "turtle "])
['horse ', 'cat ', 'dog ', 'turtle ']

最佳答案

这应该可以解决问题:

from collections import Counter

def findMode(aList):
    counter = Counter(aList)
    max_count = max(counter.values())
    return [item for item, count in counter.items() if count == max_count]

关于python - 如何编写一个找到列表模式并将其保存为字典的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996523/

相关文章:

python - 如何使用颜色在直方图上表示类别?

Python basemap : Error using shadedrelief, bluemarble 或 etopo(假经度格式?)

通过理解将 Python 列表转换为字典

python - 检查 ansible 上 Jinja2 模板中的字典中是否存在 key

python - 从 python 的覆盖范围中排除单元测试

python - 在 Python 的 For 循环中使用 'And' 运算符

python - 如何从多个列表创建 pyspark 数据框

python - 如何将字典/列表存储在数据库中?

string - '(NSObject, AnyObject )' is not convertible to ' 字符串'

python - 在字典中查找最接近的值