【问题标题】:How to create a program which counts the frequency of an integer in a list or dictionary如何创建一个计算列表或字典中整数频率的程序
【发布时间】:2019-08-07 09:46:11
【问题描述】:

我正在用 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

【问题讨论】:

    标签: python-3.x list dictionary counter frequency


    【解决方案1】:
    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))
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

      • 谢谢,我试过了,但是用户会输入整数,所以我必须使用用户想要的整数
      • 当然兄弟@SergioIzcueFreire,我们也可以这样做。您只需将用户的输入转换为上述格式。
      • @SergioIzcueFreire 无论你有什么用例。首先是收集用户的输入并将其存储在某个地方。只有这样你才能对其进行处理。所以把它存储在上面的格式并处理它。
      • 如果这对您有任何帮助,请点赞并接受我的回答。谢谢:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2018-09-21
      • 1970-01-01
      • 2014-12-18
      • 2013-10-14
      • 2016-07-27
      • 1970-01-01
      相关资源
      最近更新 更多