【问题标题】:Finding the mode and frequency of items in a Python list在 Python 列表中查找项目的模式和频率
【发布时间】:2013-10-05 17:56:57
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    如果您要计算列表中某项的频率,请尝试以下操作:

    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
    

    【讨论】:

      【解决方案2】:
      #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
      '''
      

      【讨论】:

        猜你喜欢
        • 2022-08-15
        • 2015-04-16
        • 2012-07-06
        • 1970-01-01
        • 2019-04-03
        • 2017-03-26
        • 2021-12-24
        • 2019-09-17
        • 1970-01-01
        相关资源
        最近更新 更多