Dada una lista de listas, la tarea es encontrar los elementos que son comunes en todas las sublistas.
Hay varios enfoques para hacer esta tarea. Discutamos los enfoques uno por uno.
Método #1: Usando el conjunto
# Python code to find duplicate element in all # sublist from list of list # List of list initialization Input = [ [10, 20, 30, 40], [30, 40, 60, 70], [20, 30, 40, 60, 70], [30, 40, 80, 90], ] Output = set(Input[0]) for l in Input[1:]: Output &= set(l) # Converting to list Output = list(Output) # Printing answer print(Output)
Producción:
[40, 30]
Método #2: Usar reduce
ymap
# Python code to find duplicate element in all # sublist from list of list import operator from functools import reduce # List of list initialization Input = [ [10, 20, 30, 40], [30, 40, 60, 70], [20, 30, 40, 60, 70], [30, 40, 80, 90], ] # using reduce and map out = reduce(operator.iand, map(set, Input)) # Converting into list out = list(out) # Printing output print(out)
Producción:
[40, 30]
Método #3: Usar set.intersection
# Python code to find duplicate element in all # sublist from list of list # importing reduce from functools import reduce # function for set intersection def func(a, b): return list(set(a).intersection(set(b))) # List of list initialization Input = [ [10, 20, 30, 40], [30, 40, 60, 70], [20, 30, 40, 60, 70], [30, 40, 80, 90], ] # using reduce and set.intersection out = reduce(func, Input) # Printing output print(out)
Producción:
[40, 30]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA