Dada una lista de enteros con elementos duplicados en ella. La tarea de generar otra lista, que contiene solo los elementos duplicados. En palabras simples, la nueva lista debe contener los elementos que aparecen en más de uno.
Ejemplos:
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]
Método 1: Usar el enfoque de fuerza bruta
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
Producción
[20, 30, -20, 60]
Método 2: Usar la función Counter() del módulo de colección
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)
Producción
Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1}) [1, 2, 5, 9]
Método 3: Usando el método 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
Producción
[1, 2, 5, 9]
Método 4: Usar el método de comprensión de listas
Python3
def duplicate(input_list): return list(set([x for x in input_list if input_list.count(x) > 1])) if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot
Producción
[1, 2, 5, 9]
Método 5: usar el enfoque de diccionario de lista (sin ninguna función de conteo incorporada)
Python3
def duplicate(input_list): new_dict, new_list = {}, [] for i in input_list: if not i in new_dict: new_dict[i] = 1 else: new_dict[i] += 1 for key, values in new_dict.items(): if values > 1: new_list.append(key) return new_list if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot
Producción
[1, 2, 5, 9]
Método 6: Usar operadores in, not in y el método count()
Python3
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] x = [] y = [] for i in lis: if i not in x: x.append(i) for i in x: if lis.count(i) > 1: y.append(i) print(y)
Producción
[1, 2, 5, 9]
Publicación traducida automáticamente
Artículo escrito por SaumyaBansal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA