如何创建一个程序来计算列表或字典中整数的频率

How to create a program which counts the frequency of an integer in a list or dictionary

我正在 python 中编写一个程序,提示用户输入一些整数值。该程序需要存储整数,计算每个整数的频率并显示频率。 (要存储的元素数量可以是任何...5、6、7) 我尝试从 2 个嵌套循环开始,第一个只是为了在列表中添加数字,但我知道很热实现计数器

输出应该像这样 print( Integer value, "occurs", frequency, "times)

input_list = int(input("Input the number of elements to be stored in a list: "))

list = []

 for x in range(input_list):
    list.append(input("Element - 0: "))
    list.append(input("Element - 1: "))
    list.append(input("Element - 2: "))
    list.append(input("Element - 3: "))
    list.append(input("Element - 4: "))
    print("The frequency of all elements of the list:\n")
         for y in counter(list)
         counter = 0

试试下面的代码。希望这会有所帮助。

data = [1,2,3,4,5,1,2,3,4,5,56]
data_dict = {}
for num in data:
  try:
    data_dict[num] += 1
  except:
    data_dict[num] = 1

print(data_dict)
input_len = int(input())
counts = []
for i in range(input_len):
    numbers = map(int, input().split())
    for number in numbers:
        counts.append(number)

# Get frequencies
for count in set(counts):
    print('frequency of', count, 'is', counts.count(count))