📜  Python - 过滤超序列字符串

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

Python - 过滤超序列字符串

给定一个字符串列表和子字符串,任务是编写一个Python程序来提取所有字符串,这些字符串具有可用于生成子字符串的所有字符。

例子:

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

在此,我们使用 all() 检查字符串中是否存在所有字符。字符串的迭代是使用列表理解完成的。

Python3
# Python3 code to demonstrate working of
# Filter Supersequence Strings
# Using all() + list comprehension
  
# initializing list
test_list = ["gfg", "/", "geeksforgeeks", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing substr
substr = "kgs"
  
# all() checks for all characters in strings
res = [sub for sub in test_list if all(ele in sub for ele in substr)]
  
# printing result
print("Filtered strings : " + str(res))


Python3
# Python3 code to demonstrate working of
# Filter Supersequence Strings
# Using filter() + all()
  
# initializing list
test_list = ["gfg", "/", "geeksforgeeks", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing substr
substr = "kgs"
  
# all() checks for all characters in strings
res = list(filter(lambda sub: all(ele in sub for ele in substr), test_list))
  
# printing result
print("Filtered strings : " + str(res))


输出:

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

在这里,我们使用 filter() 和 lambda函数执行过滤任务,而不是在 upper 方法中使用列表理解和条件。

蟒蛇3

# Python3 code to demonstrate working of
# Filter Supersequence Strings
# Using filter() + all()
  
# initializing list
test_list = ["gfg", "/", "geeksforgeeks", "best", "for", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing substr
substr = "kgs"
  
# all() checks for all characters in strings
res = list(filter(lambda sub: all(ele in sub for ele in substr), test_list))
  
# printing result
print("Filtered strings : " + str(res))

输出: