📜  Python|如果不包含任何字符,则从元组列表中删除元组

📅  最后修改于: 2022-05-13 01:54:30.569000             🧑  作者: Mango

Python|如果不包含任何字符,则从元组列表中删除元组

给定一个元组列表,任务是删除所有不包含任何字符值的元组。

例子:

Input: [(', ', 12), ('...', 55),
        ('-Geek', 115), ('Geeksfor', 115),]

Output: [('-Geek', 115), ('Geeksfor', 115)]

方法#1:使用列表推导

# 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)
输出:

方法#2:使用正则表达式

# 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)
输出:


方法 3:使用过滤器和 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)
输出: