Dada una lista de tuplas, que contiene enteros y strings, la tarea es eliminar todas las strings de la lista de tuplas. Ejemplos:
Input : [(1, 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware')] Output : [(1), (2), (3), (4)] Input : [('string', 'Geeks'), (2, 225), (3, '111')] Output : [(), (2, 225), (3,)]
Método #1: Usar el método filter()
Python3
# Python code to remove all strings from a list of tuples # Check function to check isinstance def check(x): return not isinstance(x, str) # creating list of tuples listOfTuples = [('string', 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware'), (5, 'Noida')] # using filter output = ([tuple(filter(check, x)) for x in listOfTuples]) # printing output print(output)
Producción:
[(), (2,), (3,), (4,), (5,)]
Método #2:
Python3
# Python code to remove all strings from a list of tuples # Creating list of tuples listOfTuples = [('string', 'Geeks'), (2, 225), (3, '111'), (4, 'Cyware'), (5, 'Noida')] output = [tuple(j for j in i if not isinstance(j, str)) for i in listOfTuples] # printing output print(output)
Producción:
[(), (2, 225), (3,), (4,), (5,)]
Método #3: Usando el método type()
Python3
# Python code to remove all strings from a list of tuples # creating list of tuples listOfTuples = [('string', 'Paras'), (2, 'Jain'), (3, 'GFG'),(4, 'Cyware'), (5, 'Noida')] x=[] for i in listOfTuples: p=[] for j in i: if(not (type(j) is str)): p.append(j) p=tuple(p) x.append(p) # printing output print(x)
Producción
[(), (2,), (3,), (4,), (5,)]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA