Dada una lista de tuplas, la tarea es eliminar todas aquellas tuplas que no contienen ningún valor de carácter.
Ejemplo:
Input: [(', ', 12), ('...', 55), ('-Geek', 115), ('Geeksfor', 115),] Output: [('-Geek', 115), ('Geeksfor', 115)]
Método #1: Usar la comprensión de listas
# Python code to remove all those # elements from list of tuple # which does not contains any alphabet. # List initialization List = [(', ', 12), ('Paras', 5), ('jain.', 11), ('...', 55), ('-Geek', 115), ('Geeksfor', 115), (':', 63), ('Data', 3), ('-', 15), ('Structure', 32), ('Algo', 80),] # Using list comprehension out = [(a, b) for a, b in List if any(c.isalpha() for c in a)] # Printing output print(out)
Producción:
[(‘Paras’, 5), (‘jain.’, 11), (‘-Geek’, 115), (‘Geeksfor’, 115), (‘Data’, 3), (‘Structure’, 32) , (‘Algo’, 80)]
Método #2: Usando Regex
# Python code to remove all those # elements from list of tuple # which does not contains any alphabet. # List initialization List = [(', ', 12), ('Paras', 5), ('jain.', 11), ('...', 55), ('-Geek', 115), ('Geeksfor', 115), (':', 63), ('Data', 3), ('-', 15), ('Structure', 32), ('Algo', 80),] # Importing import re # Using regex out = [t for t in List if re.search(r'\w', t[0])] # Printing output print(out)
Producción:
[(‘Paras’, 5), (‘jain.’, 11), (‘-Geek’, 115), (‘Geeksfor’, 115), (‘Data’, 3), (‘Structure’, 32) , (‘Algo’, 80)]
Método 3: uso de filtro y lambda
# Python code to remove all those # elements from list of tuple # which does not contains any alphabet. # List initialization List = [(', ', 12), ('Paras', 5), ('jain.', 11), ('...', 55), ('-Geek', 115), ('Geeksfor', 115), (':', 63), ('Data', 3), ('-', 15), ('Structure', 32), ('Algo', 80),] # Using filter out = filter(lambda x:any(c.isalpha() for c in x[0]), List) # Converting in list out = list(out) # Printing output print(out)
Producción:
[(‘Paras’, 5), (‘jain.’, 11), (‘-Geek’, 115), (‘Geeksfor’, 115), (‘Data’, 3), (‘Structure’, 32) , (‘Algo’, 80)]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA