查找Python列表中项目的模式和频率

时间:2013-09-29 23:43:06

标签: python for-loop python-3.x mode

您如何在Python列表中找到项目的模式和频率?

这就是我所拥有的:

elif user_option == 7:
    for score in scores_list:
        count = scores_list.count(score)
        print ("mode(s), occuring" + str(count) + ":")
        print(score)

我需要做的是打印出如果用户输入一组得分最多的分数,其中2出现在相同的时间,我还必须显示实际得分。但这是我测试时得到的结果:

Select an option above:7
mode(s), occuring2:
45.0
mode(s), occuring2:
45.0
mode(s), occuring1:
67.0

2 个答案:

答案 0 :(得分:2)

如果您正在尝试计算列表项的频率,请尝试以下方法:

from collections import Counter
data = Counter(your_list_in_here)
data.most_common()   # Returns all unique items and their counts
data.most_common(1)  # Returns the highest occurring item

答案 1 :(得分:0)

#Here is a method to find mode value from given list of numbers
#n : number of values to be entered by the user for the list
#x : User input is accepted in the form of string
#l : a list is formed on the basis of user input

n=input()
x=raw_input()
l=x.split()
l=[int(a) for a in l]  # String is converted to integer
l.sort() # List is sorted
[#Main code for finding the mode
i=0
mode=0
max=0
current=-1
prev=-1
while i<n-1:
 if l\[i\]==l\[i+1\]:
   mode=mode+1
     current=l\[i\]
 elif l\[i\]<l\[i+1\]:
   if mode>=max:
     max=mode
     mode=0
     prev=l\[i\]
 i=i+1
if mode>max:
    print current
elif max>=mode:
    print prev][1]

'''Input
8
6 3 9 6 6 5 9 3

Output
6
'''