Python | Comprobar si una lista es un subconjunto de otra

A veces nos encontramos con el problema de verificar si una lista es solo una extensión de la lista, es decir, solo un superconjunto de una lista. Este tipo de problemas son bastante populares en la programación competitiva. Tener abreviaturas ayuda a la causa. Analicemos varias formas de lograr esta tarea en particular.

Método #1: Usar la función all() 

all() se usa para verificar todos los elementos de un contenedor en una sola línea. Comprueba la existencia de todos los elementos de una lista en otras listas. 

Python3

# Python3 code to demonstrate
# to check if list is subset of other
# using all()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original sub list : " + str(sub_list))
 
# using all() to
# check subset of list
flag = 0
if(all(x in test_list for x in sub_list)):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

Producción : 

Original list : [9, 4, 5, 8, 10]
Original sub list : [10, 5, 4]
Yes, list is subset of other.

Método #2: Usar la  función set.issubset()

El método más utilizado y recomendado para verificar una sublista. Esta función está hecha a medida para realizar la tarea particular de verificar si una lista es un subconjunto de otra. 

Python3

# Python3 code to demonstrate
# to check if list is subset of other
# using issubset()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original sub list : " + str(sub_list))
 
# using issubset() to
# check subset of list
flag = 0
if(set(sub_list).issubset(set(test_list))):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

Producción : 

Original list : [9, 4, 5, 8, 10]
Original sub list : [10, 5]
Yes, list is subset of other.

Método #3: Usando la  función set.intersection()

Otro método más que trata con conjuntos, este método verifica si la intersección de ambas listas termina siendo la sublista que estamos verificando. Esto confirma que una lista es un subconjunto de la otra.

Python3

# Python3 code to demonstrate
# to check if list is subset of other
# using intersection()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original sub list : " + str(sub_list))
 
# using intersection() to
# check subset of list
flag = 0
if((set(sub_list) & set(test_list)) == set(sub_list)):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

Producción : 

Original list : [9, 4, 5, 8, 10]
Original sub list : [10, 5]
Yes, list is subset of other.

Método #4: Usar iteración y contador 

Usando el conteo de elementos en ambas listas para verificar si la segunda lista es un subconjunto de la primera lista. 

Python3

# Python3 code to demonstrate
# to check if list is subset of other
 
# Importing
from collections import Counter
 
 
def checkInFirst(a, b):
     # getting count
    count_a = Counter(a)
    count_b = Counter(b)
 
    # checking if element exists in second list
    for key in count_b:
        if key not in count_a:
            return False
        if count_b[key] > count_b[key]:
            return False
    return True
 
 
# initializing list
a = [1, 2, 4, 5]
b = [1, 2, 3]
 
# Calling function
res = checkInFirst(a, b)
 
# Printing list
print("Original list : " + str(a))
print("Original sub list : " + str(b))
 
if res == True:
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")
 
# Added by Paras Jain(everythingispossible)

Producción : 

Original list : [1, 2, 4, 5]
Original sub list : [1, 2, 3]
No, list is not subset of other.

Método #5: Usando el índice establecido

Python3

# Python3 code to demonstrate
# to check if list is subset of other
 
# initializing list
one = [1, 2, 3, 4, 5]
two = [1, 2]
 
# using set to find if element exists in another list
result = set(x in one for x in two)
 
flag = 0
 
for ans in result:
    if ans == False:
        flag = 1
 
# Printing list
print("Original list : " + str(one))
print("Original sub list : " + str(two))
 
if flag == 0:
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")
 
# Added by Paras Jain(everythingispossible)

Producción : 

Original list : [1, 2, 3, 4, 5]
Original sub list : [1, 2]
Yes, list is subset of other.

Método #6: Usar functools.reduce

Python3

from functools import reduce
from operator import and_ 
 
# main containing checker
def contains(superset, subset) -> bool:
     
    # creates a list of boolean values and
    # combines them using the and operator
    return reduce(and_, [i in superset for i in subset])
 
 
# creating some lists for testing
superset = [3, 4, 5, 6]
subset = [4, 5]
not_subset = [4, 5, 7]
 
# print whether or not the
# subset is in the superset
print(f"{subset} is in {superset}: {contains(superset,
subset)}")
print(f"{not_subset} is in {superset}: {contains(superset,
not_subset)}")

Producción:

[4, 5] is in [3, 4, 5, 6]: True
[4, 5, 7] is in [3, 4, 5, 6]: False

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *