【问题标题】:Trying to get a count of duplicate elements试图计算重复元素的数量
【发布时间】:2021-12-12 05:08:19
【问题描述】:

我是 python 新手,我只是想计算重复元素的数量。我的代码如下所示:

n=int(input("Enter the number of products to be stored in a list : "))

list1=[]

for i in range(n):
  items=int(input("value for product " + str(i+1) + " : "))
    list1.append(items)
    
dup=[]

for a in list1:
    if list1.count(a)>1:
        dup.append(a)

print("Count of duplicate elements in the list: ",dup)

输出:

Enter the number of products in a list : 5
value for product 1 : 4
value for product 2 : 4
value for product 3 : 4
value for product 4 : 1
value for product 5 : 5
Count of duplicate elements in the list:  [4, 4, 4]

答案应该是 1,因为它只是数字 4 是重复值,但我得到了上面的输出。有人可以请教吗?

【问题讨论】:

  • 您的代码有很多地方需要改进,但只是一个快速修复,您可以在上次打印时使用len(set(dup)) 代替dup
  • 您能否详细说明为什么当您实际上是 print 处理列表的内容时,您希望此代码会导致 1printing 任何列表的内容何时会产生一个整数?您是否尝试过修改逻辑以仅将元素添加到dup(如果它们尚不存在)?如果您将您在此处看到的问题分解为较小的需求,那么它们都是以前在这里被问过很多次的问题。您能否总结一下您所做的研究,并解释为什么不符合您的要求? How to Ask

标签: python duplicates


【解决方案1】:

您正在将重复项添加到 dup,即使它已经在列表中。您应该在添加之前检查它。

for a in list1:
    if list1.count(a)>1 and a not in dup:
        dup.append(a)

如果你想要重复的计数,你应该打印dup的长度,而不是它的内容。

print("Count of duplicate elements in the list: ",len(dup))

您也可以将dup 设为集合而不是列表。然后忽略重复项。通过初始化执行此操作:

dup = set()

并使用.add() 而不是.append()

【讨论】:

    【解决方案2】:

    如果 Count 大于 1,则检查 a 是否不在 dup 列表中,然后将 a 添加到其中。 最后,打印dup列表的长度

    n=int(input("Enter the number of products to be stored in a list : "))
    
    list1=[]
    
    for i in range(n):
        item = int(input("value for product " + str(i+1) + " : "))
        list1.append(item)
        
    dup = []
    
    for a in list1:
        if (list1.count(a) > 1) and (a not in dup):
            dup.append(a)
    
    print("Count of duplicate elements in the list: ", len(dup))
    
    

    【讨论】:

      【解决方案3】:

      不管怎样,这里有一个更高级的解决方案:

      通常要计算多个元素的出现次数,最简单的方法是使用Counter。一旦你有了它,你只需要获取多次出现的项目的数量。

      list1 = [4, 4, 4, 1, 5]
      # ---
      from collections import Counter
      
      counts = Counter(list1)  # > Counter({4: 3, 1: 1, 5: 1})
      total = sum(count>1 for count in counts.values())
      
      print(total)  # -> 1
      

      这个sum() 有效,因为count>1 返回FalseTrue,以及False == 0True == 1

      【讨论】:

        【解决方案4】:

        使用 numpy 库,您可以使用 numpy.unique 计算 numpy 数组中的每次出现次数:

        import numpy
        
        for a in list1: 
            if list1.count(a)>1:
                dup.append(a)
        
        dup_array = numpy.array(dup)
        unique, counts = numpy.unique(dup, return_counts=True)
        dict(zip(unique, counts))
        

        【讨论】:

        • 你不需要 NumPy 来做这个,标准库有Counter,我刚刚发布了an answer
        • @wjandrea 我认为这是一个有效的替代方案
        【解决方案5】:

        一个选项可以是使用字典,这样您不仅可以知道重复的数量,还可以知道重复的内容和出现的次数。

        n = int(input("Enter the number of products to be stored in a list : "))  # 
        
        I have entered 5
        
        list1 = []
        
        for i in range(n):
            items = int(input("value for product " + str(i + 1) + " : "))
            list1.append(items)
        
        dup = {}
        
        for a in list1:
            if list1.count(a) > 1:
                dup[a] = dup.get(a, 0)+1
        
        print("Count of duplicate elements in the list: ", len(dup))
        print(dup)
        

        结果是:

        Enter the number of products to be stored in a list : 5
        value for product 1 : 4
        value for product 2 : 4
        value for product 3 : 4
        value for product 4 : 2
        value for product 5 : 2
        Count of duplicate elements in the list:  2
        {4: 3, 2: 2}
        

        【讨论】:

          【解决方案6】:

          这很简单。您可以使用集合中的 Counter 来计算列表中每个元素的出现次数。然后你可以按如下方式计算不唯一的元素。

          from collections import Counter
          n=int(input("Enter the number of products to be stored in a list : "))
          
          list1=[]
          
          for i in range(n):
              items=int(input("value for product " + str(i+1) + " : "))
              list1.append(items)
          dup_dict=Counter(list1)
          count=0
          for i in dup_dict.values():
              if(i!=1):
                  count+=1
          
          print("Count of duplicate elements in the list: ",count)
          

          【讨论】:

            猜你喜欢
            • 2021-12-22
            • 2020-12-01
            • 1970-01-01
            • 2014-11-12
            • 1970-01-01
            • 2013-08-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多