【问题标题】:Find and return the elements that are repeated exactly twice in the list查找并返回列表中恰好重复两次的元素
【发布时间】:2020-02-16 15:48:24
【问题描述】:

我想找到并返回完全重复的元素 列表中的两次。我写了这段代码,但它也输出了重复三次的数字。

如何打印只重复两次的数字?

def printRepeating(arr,size) : 
count = [0] * size 
print(" Repeating elements are ",end = "") 
for i in range(0, size) : 
    if(count[arr[i]] == 1) : 
        print(arr[i], end = " ") 
    else : 
        count[arr[i]] = count[arr[i]] + 1

 arr = [2, 8, 4, 6, 1, 2, 8, 4, 7, 9, 4, 5] 
 arr_size = len(arr) 
 printRepeating(arr, arr_size) 

【问题讨论】:

    标签: python arrays duplicates


    【解决方案1】:

    试试这个,更简洁:

    import collections
    
    arr = [2, 8, 4, 6, 1, 2, 8, 4, 7, 9, 4, 5] 
    repeats = [
        item 
        for item, count in collections.Counter(arr).items() 
        if count == 2
    ]
    print(repeats)
    

    【讨论】:

    • counter = collections.Counter(arr).items() 正在计算所有元素的重复次数。 dict_items([(2, 2), (8, 2), (4, 3), (6, 1), (1, 1), (7, 1), (9, 1), (5, 1) ]) 剩下的是一个列表理解,它遍历字典并只获取 count==2 的列表
    【解决方案2】:
    arr = [2, 8, 4, 6, 1, 2, 8, 4, 7, 9, 4, 5] 
    [x for x in set(arr) if arr.count(x) == 2]
    
    Out[1]:
        [2, 8]
    

    【讨论】:

      【解决方案3】:

      如果您只想删除重复项,可以使用

      arr = [2, 8, 4, 6, 1, 2, 8, 4, 7, 9, 4, 5] 
      set(arr)
      

      否则使用建议的收集方法

      【讨论】:

        【解决方案4】:

        另一个简短的解决方案:

        arr = [2, 8, 4, 6, 1, 2, 8, 4, 7, 9, 4, 5] 
        print(set([x for x in arr if arr.count(x) == 2])) # set is used to remove duplicates
        # print(list(set([x for x in arr if arr.count(x) == 2]))) to print it as a list
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-10
          • 2014-04-21
          • 2012-12-07
          • 2023-02-24
          • 2013-03-24
          • 2021-09-12
          相关资源
          最近更新 更多