简体   繁体   English

查找并返回列表中恰好重复两次的元素

[英]Find and return the elements that are repeated exactly twice in the list

I want to find and return the elements that are repeated exactly twice in the list.我想查找并返回列表中重复两次的元素。 I wrote this code but it also outputs the numbers that repeat three times.我写了这段代码,但它也输出了重复三次的数字。

How do I print out numbers that only repeat twice?如何打印出只重复两次的数字?

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) 

try this, it is more concise:试试这个,它更简洁:

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)
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]

if you want just to remove duplicates you can use如果您只想删除重复项,则可以使用

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

otherwise use the collection method advised否则使用建议的收集方法

an other short solution:另一个简短的解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM