如何跟踪此列表中的频率?

问题描述 投票:0回答:2

我想弄清楚如何跟踪用户输入的列表中的数字的频率。我的意思是:假设有人输入45次,52次,3次,22次,代码将打印出类似“频率:45-2,52-3和22-1”的内容。提出此问题的其他代码适用于已在代码中创建的列表,但这一个是不同的,因为用户正在添加到列表中。

import sys

print ("After inputting this data, the sum, average, maximum and minimum 
number will be printed")

temperatureList = list()

weather=int(input("Enter the amount of days that you are looking at for 
the weather:"))

print("Enter the high temperature for those next days: ")

for i in range(int(weather)):
   k=int(input(""))
   temperatureList.append(int(k))
sm=sum(temperatureList)
avg=sm/weather
print("SUM = ",sm)
print("AVERAGE = ",avg)

temperatureList.sort()
print("This is the numbers from low to high", temperatureList)
print("Maximum number in the list is:", max(temperatureList), "and the 
minimum number is: ", min(temperatureList))

while True:
   action = int(input("Input add if you want to add to the list again. Or 
remove if you want to remove from the list, or end if you want to end this 
program"))

   if action == add:
      print("Enter what you want to be added ")
      add = int(input(""))
      temperatureList.append(add)
      print(temperatureList)
      sm = sum(temperatureList)
      avg = sm / weather
      print("SUM = ", sm)
      print("AVERAGE = ", avg)
      temperatureList.sort()
      print("This is the numbers from low to high", temperatureList)

   elif action == remove:
      if len(temperatureList) > 1:
         del temperatureList[-1]
         print(temperatureList)
         sm = sum(temperatureList)
         avg = sm / weather
         print("SUM = ", sm)
         print("AVERAGE = ", avg)

  else:
     print("Everything removed from the list")

   elif action == end:
      sys.exit()
python
2个回答
0
投票

你需要所谓的直方图。您可以使用Python字典创建一个;使用您获得的答案作为字典的键,答案计为相应的值。每当您从用户那里得到答案时,请检查字典是否已有该答案的条目。如果不是,请将值设置为1。如果密钥存在,请获取计数,将其增加1,然后存储新计数。然后,您可以在开始另一轮循环之前打印字典(或其中的某些表示)。

如果您不熟悉Python词典,请首先查看documentation


-1
投票

GeeksforGeeks上有一个很好的例子。阅读本文将有助于您解决问题。

以下是他们为解决方案提供的Python代码:

# Python program to count the frequency of  
# elements in a list using a dictionary 

def CountFrequency(my_list): 

    # Creating an empty dictionary  
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1

    for key, value in freq.items(): 
        print ("% d : % d"%(key, value)) 

# Driver function 
if __name__ == "__main__":  
    my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] 

    CountFrequency(my_list) 

这简单地遍历列表,使用列表中的每个不同元素作为字典中的键并将该键的相应计数存储为值。

它的时间复杂度为O(n),其中n是列表的长度,因为它迭代列表中的每个值。

© www.soinside.com 2019 - 2024. All rights reserved.