2013-09-29 46 views
0

如何找到Python列表中項目的模式和頻率?查找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

,如果你想計算列表項的頻率試試這個:

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 
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 
''' 
相關問題