【问题标题】:Python 3 - Find the Mode of a ListPython 3 - 查找列表的模式
【发布时间】:2015-07-12 04:48:49
【问题描述】:
def mode(L):

    shows = []
    modeList = []

    L.sort()

    length = len(L)

    for num in L:
        count = L.count(num)
        shows.append(count)

    print 'List = ', L

    maxI = shows.index(max(shows))

    for i in shows:
        if i == maxI:
            if modeList == []:
                mode = L[i]
                modeList.append(mode)
                print 'Mode = ', mode
            elif mode not in modeList:
                mode = L[i]
                modeList.append(mode)
                print 'Mode = ', mode
            return mode


mode(L)  

我似乎无法正确地遍历我的列表... 我可以使用第二个 for 循环成功获得第一个返回 Mode = 87 的模式,但是我无法让它搜索列表的其余部分,因此它也会返回 Mode = 92

我已经删除了我在Mode = 92 的尝试,有人可以帮忙填空吗?

【问题讨论】:

  • 你能显示你正在测试的列表吗?没有它,您对 87 和 92 等特定值的引用就没有多大意义。
  • L = [98,75,92,87,89,90,92,87]
  • 我不太明白你想要完成什么,但是在“for i in show:”中,当“if modeList == []:”和“elif mode”时会做同样的事情不在 modeList 中:”,因此它们可以合并为一个“如果 modeList == [] 或模式不在 modeList 中:”

标签: python python-3.x


【解决方案1】:

您的代码的第一个问题是您的循环中有一个return 语句。当它到达时,函数结束,其余的迭代永远不会发生。您应该删除 return mode 并在循环结束后将 return modeList 放在函数的顶层。

第二个问题是您在最后一个循环中的计数、索引和值的逻辑非常混乱。它有时会起作用,因为您正在测试的输入往往具有也是有效索引的计数,但它几乎是偶然的。您要做的是找到最大计数,然后找到具有该计数的所有值。如果您将zip 输入列表Lshows 列表一起使用,则可以完全避免使用索引:

max_count = max(shows)
for item, count in zip(L, shows):
    if count == max_count and item not in modeList:
        print("mode =", item)
        modeList.append(item)

return modeList

虽然这应该可以解决您遇到的直接问题,但我觉得我应该建议一种替代实现,它会更快、更高效(更不用说需要更少的代码)。而不是使用list.count 来查找列表中每个值的出现次数(这需要O(N**2) 时间),您可以使用collections.Counter 来计算O(N) 时间。其余的代码也可以稍微简化一下:

from collections import Counter

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多