Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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 给出数据模式的代码(不应使用统计信息下可用的函数)_Python_Database_For Loop_If Statement_Statistics - Fatal编程技术网

Python 给出数据模式的代码(不应使用统计信息下可用的函数)

Python 给出数据模式的代码(不应使用统计信息下可用的函数),python,database,for-loop,if-statement,statistics,Python,Database,For Loop,If Statement,Statistics,我试图写一个代码,给出数据的模式。我不应该使用统计数据下可用的函数 模块,但我可以使用内置函数,如max、min、sum等 list1 = [1,2,3,4,5,4,3,2,1,2,3,3,4,2,1,3,2,1,3,5] time=0 freq1=0 freq2=0 freq3=0 freq4=0 freq5=0 for i in list1: if list1[i]==1: time+=time freq1=time elif list1[i]

我试图写一个代码,给出数据的模式。我不应该使用统计数据下可用的函数 模块,但我可以使用内置函数,如max、min、sum等

list1 = [1,2,3,4,5,4,3,2,1,2,3,3,4,2,1,3,2,1,3,5]
time=0
freq1=0
freq2=0
freq3=0
freq4=0
freq5=0
for i in list1:
    if list1[i]==1:
        time+=time
        freq1=time
    elif list1[i]==2:
        time+=time
        freq2=time
    elif list1[i]==3:
        time+=time
        freq3=time
    elif list1[i]==4:
        time+=time
        freq4=time
    elif list1[i]==5:
        time+=time
        freq5=time
list2=[freq1,freq2,freq3,freq4,freq5]
print(max(list2))
这是我得到的

0
>>> 

我做错了什么?

你在不断增加时间。时间=0。时间+时间=0,因此频率值错误。 使用以下方法解决此问题:

time+=1 
除非为每个可能的变量启动一个新的时间,否则也不会起作用。您可以对每个案例使用freqn+=1,它的工作原理相同


有很多更有效的方法可以做到这一点,但这就是代码中的错误

你的方法是错误的,原因有很多首先对于您编写的程序,您不需要
时间,您每次都在向自身添加时间。现在
time
是0,所以即使在多次添加之后,也会得到0Third,您正在迭代所有元素,而不是它们的索引,因此您需要检查
i
,而不是检查
list[i]
。所以应该是这样的:

list1 = [1,2,3,4,5,4,3,2,1,2,3,3,4,2,1,3,2,1,3,5]

freq1=0
freq2=0
freq3=0
freq4=0
freq5=0
for i in list1:
    if i==1:
        freq1 += 1
    elif i==2:
        freq2 += 1
    elif i==3:
        freq3 += 1
    elif i==4:
        freq4 += 1
    elif i==5:
        freq5 += 1
list2=[freq1,freq2,freq3,freq4,freq5]
print(max(list2))
但即使在所有这些之后,你也会得到一个值的最大出现次数,而不是最大时间出现的值。上述程序的结果是
6
。这是模式
3
出现
6次的计数。现在,为了获得模式本身,您需要一些其他的数据结构,列表列表或元组列表,但最好的是字典

所以像这样的事情是最甜蜜的:

list1 = [1,2,3,4,5,4,3,2,1,2,3,3,4,2,1,3,2,1,3,5]
d = {}
for num in list1:
    d[num] = d.get(num,0) + 1
# at this point, d looks like this:
# {1: 4, 2: 5, 3: 6, 4: 3, 5: 2}

# Then either:
print('mode =',max(d,key = lambda key:d[key]))
# outputs: 
# mode = 3

# or
print('mode = {0}, occurs {1} times'.format(*max(list(d.items()),key = lambda item:item[1])))
# outputs:
# mode = 3, occurs 6 times

您的代码段与发布的结果不匹配。请用适当的字体编辑您的问题