📌  相关文章
📜  Python - 字符串列表中所有出现的子字符串

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

Python - 字符串列表中所有出现的子字符串

给定一个字符串列表和一个子字符串列表。任务是从字符串列表中提取所有出现的 substring 。

例子:

方法 #1:使用循环 + in运算符

以上功能的组合可以解决这个问题。在这里,我们运行一个循环来提取列表中的所有字符串以及所有子字符串。 in运算符用于检查子字符串是否存在。

Python3
# Python3 code to demonstrate working of 
# Strings with all Substring Matches
# Using loop + in operator
  
# initializing list
test_list = ["gfg is best", "gfg is good for CS",
             "gfg is recommended for CS"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Substring List 
subs_list = ["gfg", "CS"]
  
res = []
for sub in test_list:
    flag = 0
    for ele in subs_list:
          
        # checking for non existance of 
        # any string 
        if ele not in sub:
            flag = 1 
            break
    if flag == 0:
        res.append(sub)
  
# printing result 
print("The extracted values : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Strings with all Substring Matches
# Using all() + list comprehension
  
# initializing list
test_list = ["gfg is best", "gfg is good for CS",
             "gfg is recommended for CS"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Substring List 
subs_list = ["gfg", "CS"]
  
# using all() to check for all values
res = [sub for sub in test_list 
       if all((ele in sub) for ele in subs_list)]
  
# printing result 
print("The extracted values : " + str(res))


输出:

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

这是一种单线方法,借助它我们可以执行此任务。在这里,我们使用 all() 检查所有值是否存在,并且使用列表理解来迭代所有容器。

蟒蛇3

# Python3 code to demonstrate working of 
# Strings with all Substring Matches
# Using all() + list comprehension
  
# initializing list
test_list = ["gfg is best", "gfg is good for CS",
             "gfg is recommended for CS"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Substring List 
subs_list = ["gfg", "CS"]
  
# using all() to check for all values
res = [sub for sub in test_list 
       if all((ele in sub) for ele in subs_list)]
  
# printing result 
print("The extracted values : " + str(res))

输出: