0

你如何找到 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
4

2 回答 2

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
于 2013-09-29T23:46:58.107 回答
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
'''
于 2016-07-29T13:22:43.300 回答