📜  Python - 用特定字符的字符串过滤元组

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

Python - 用特定字符的字符串过滤元组

给定一个元组列表,提取具有由特定字符组成的字符串的元组。

方法 #1:使用all() +列表推导

在这里,我们检查字符中的字符串,使用 in运算符和 all() 用于检查元组中的所有元素是否具有由某些字符组成的字符串。

Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# Using all() + list comprehension
  
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing char_str
char_str = 'gfestb'
  
# nested all(), to check for all characters in list, 
# and for all strings in tuples
res = [sub for sub in test_list if all(
    all(el in char_str for el in ele) for ele in sub)]
  
# printing result
print("The filtered tuples : " + str(res))


Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# Using filter() + lambda + all()
  
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing char_str
char_str = 'gfestb'
  
# nested all(), to check for all characters in list, 
# and for all strings in tuples filter() is used 
# to extract tuples
res = list(filter(lambda sub: all(all(el in char_str for el in ele)
                                  for ele in sub), test_list))
  
# printing result
print("The filtered tuples : " + str(res))


输出:

方法 #2:使用filter() + lambda + all()

与上述方法类似,不同之处在于 filter() + lambda 用于执行过滤任务。

蟒蛇3

# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# Using filter() + lambda + all()
  
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing char_str
char_str = 'gfestb'
  
# nested all(), to check for all characters in list, 
# and for all strings in tuples filter() is used 
# to extract tuples
res = list(filter(lambda sub: all(all(el in char_str for el in ele)
                                  for ele in sub), test_list))
  
# printing result
print("The filtered tuples : " + str(res))

输出: