Python 查找并返回列表中重复两次的元素
我想找到并返回完全重复的元素 名单上有两次。我写了这段代码,但它也输出重复三次的数字 如何打印出只重复两次的数字Python 查找并返回列表中重复两次的元素,python,arrays,duplicates,Python,Arrays,Duplicates,我想找到并返回完全重复的元素 名单上有两次。我写了这段代码,但它也输出重复三次的数字 如何打印出只重复两次的数字 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 = " ") el
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)
试试这个,它更简洁:
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]
set(arr)
否则,使用建议的收集方法另一个简短的解决方案:
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
counter=collections.counter(arr).items()计算所有元素的重复次数。dict_项([(2,2),(8,2),(4,3),(6,1),(1,1),(7,1),(9,1),(5,1)])其余的是一个列表理解,它在字典中迭代,只对计数=2的项进行fech
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