Dada una tupla de listas, la tarea es encontrar el número de listas en una tupla. Este es un problema muy básico pero puede ser útil al hacer alguna aplicación de utilidad. Método #1: Usar len
Python3
# Python code to find number of list in a tuple # Initial list Input1 = ([1, 2, 3, 4], [5, 6, 7, 8]) Input2 = ([1, 2], [3, 4], [5, 6]) Input3 = ([9, 8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3]) # Using len to find no of list in tuple Output1 = len(Input1) Output2 = len(Input2) Output3 = len(Input3) # Printing print("Initial list :") print(Input1) print("No of list in tuples are :") print(Output1) print("\n") print("Initial list :") print(Input2) print("No of list in tuples are :") print(Output2) print("\n") print("Initial list :") print(Input3) print("No of list in tuples are :") print(Output3) print("\n")
Producción:
Initial list : ([1, 2, 3, 4], [5, 6, 7, 8]) No of list in tuples are : 2 Initial list : ([1, 2], [3, 4], [5, 6]) No of list in tuples are : 3 Initial list : ([9, 8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3]) No of list in tuples are : 2
Método n.º 2: usar la función y la instancia
Python3
# Python code to find number of list in a tuple # Using find function def find(Input): if isinstance(Input, list): return 1 else: return len(Input) # List initialization Input1 = ([1, 2, 3, 4], [5, 6, 7, 8]) Input2 = ([1, 2], [3, 4], [5, 6]) Input3 = ([9, 8, 7, 6, 5, 4, 3, 2, 1]) # using find Output1 = find(Input1) Output2 = find(Input2) Output3 = find(Input3) # printing print("Initial list :") print(Input1) print("No of list in tuples are :") print(Output1) print("\n") print("Initial list :") print(Input2) print("No of list in tuples are :") print(Output2) print("\n") print("Initial list :") print(Input3) print("No of list in tuples are :") print(Output3) print("\n")
Producción:
Initial list : ([1, 2, 3, 4], [5, 6, 7, 8]) No of list in tuples are : 2 Initial list : ([1, 2], [3, 4], [5, 6]) No of list in tuples are : 3 Initial list : [9, 8, 7, 6, 5, 4, 3, 2, 1] No of list in tuples are : 1
Método #3: Usar type() .type() devuelve el tipo de datos de la variable. Si en caso de que la tupla tenga diferentes tipos de datos además de la lista, entonces len() falla. Itere sobre la tupla y verifique el tipo de datos de cada elemento
Python3
# Python code to find number of list in a tuple # Initial list Input1 = ([1, 2, 3, 4], [5, 6, 7, 8],5) # Using type() to find no of list in tuple Output1=0 for i in Input1: if(type(i) is list): Output1+=1 # Printing print("Initial list :") print(Input1) print("No of list in tuples are :") print(Output1)
Producción
Initial list : ([1, 2, 3, 4], [5, 6, 7, 8], 5) No of list in tuples are : 2
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA