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

时间:2019-05-05 21:19:52

标签: 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 ']

3 个答案:

答案 0 :(得分:4)

这应该可以解决问题:

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]

答案 1 :(得分:0)

for

您可以在没有字典的情况下更快地执行此操作,但是它可以那样工作

答案 2 :(得分:0)

from collections import defaultdict
def findMode(aList):
    dic = defaultdict(int)
    for i in aList:
        dic[i]+=1
    mv = max(dic.values())
    return [i for i in dic if dic[i]==mv]

findMode([4,3,4,3,2,1,4,5,3,3,4,5,1,4,1,4,5])
# output [4]

findMode(["horse ", "cat ", "dog ", "turtle ","horse ", "cat ", "dog ", "turtle "])
# output ['horse ', 'cat ', 'dog ', 'turtle ']