Python|从整数列表中打印重复项的程序
给定一个包含重复元素的整数列表。生成另一个列表的任务,其中仅包含重复的元素。简单来说,新列表应该包含出现多个的元素。
例子 :
Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]
Input : list = [-1, 1, -1, 8]
Output : output_list = [-1]
方法 1:使用蛮力方法
Python3
# Python program to print
# duplicates from a list
# of integers
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
50, -20, 60, 60, -20, -20]
print (Repeat(list1))
# This code is contributed
# by Sandeep_anand
Python3
from collections import Counter
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
d = Counter(l1)
print(d)
new_list = list([item for item in d if d[item]>1])
print(new_list)
Python3
# program to print duplicate numbers in a given list
# provided input
list = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
new = [] # defining output list
# condition for reviewing every
# element of given input list
for a in list:
# checking the occurrence of elements
n = list.count(a)
# if the occurrence is more than
# one we add it to the output list
if n > 1:
if new.count(a) == 0: # condition to check
new.append(a)
print(new)
# This code is contributed by Himanshu Khune
输出 :
[20, 30, -20, 60]
方法 2:使用收集模块中的 Counter()函数
Python3
from collections import Counter
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
d = Counter(l1)
print(d)
new_list = list([item for item in d if d[item]>1])
print(new_list)
输出
Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})
[1, 2, 5, 9]
方法 3:使用 count() 方法
Python3
# program to print duplicate numbers in a given list
# provided input
list = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
new = [] # defining output list
# condition for reviewing every
# element of given input list
for a in list:
# checking the occurrence of elements
n = list.count(a)
# if the occurrence is more than
# one we add it to the output list
if n > 1:
if new.count(a) == 0: # condition to check
new.append(a)
print(new)
# This code is contributed by Himanshu Khune
输出:
[1, 2, 5, 9]