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

python - 如何跟踪此列表中的频率?,第1张

我想弄清楚如何跟踪用户输入列表中数字的频率。我的意思是:假设某人输入两次45,两次52和一次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()

最佳答案:

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-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是列表的长度,因为它会遍历列表中的每个值。

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复