Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3-查找列表的模式_Python_Python 3.x - Fatal编程技术网

Python 3-查找列表的模式

Python 3-查找列表的模式,python,python-3.x,Python,Python 3.x,我似乎无法正确地遍历我的列表。。。 我可以使用第二个for循环成功地获得返回Mode=87的第一个模式,但是,我无法让它搜索列表的其余部分,以便它也返回Mode=92 我已经删除了我在Mode=92上的尝试,有人能帮我填空吗?代码的第一个问题是循环中有一个return语句。当到达时,函数结束,其余的迭代永远不会发生。在循环结束后,您应该删除returnmode,而将returnmodelist放在函数的顶层 第二个问题是,关于上一个循环中的计数、索引和值,您的逻辑非常混乱。它在某些时候起作用,因

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


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

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

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

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)  
虽然这应该解决您面临的直接问题,但我觉得我应该建议一种更快、更高效的替代实现(更不用说需要更少的代码)。与使用
list.count
查找列表中每个值的出现次数(需要
O(N**2)
time)不同,您可以使用
collections.Counter
O(N)
time中计数。代码的其余部分也可以简化一点:

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

你能出示你正在测试的列表吗?如果没有这一点,您对87和92等特定值的引用就没有多大意义。L=[98,75,92,87,89,90,92,87]我不太理解您试图实现的目标,但是在“for I in shows”中:“if modeList=[]:”和“elif mode not in modeList:”时会执行相同的操作,如果modeList=[]则“elif mode not in modeList:”因此它们可以组合成一个“if modeList=[]或模式不在modeList中:
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]