📌  相关文章
📜  Python – 具有所有给定列表字符的字符串

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

Python – 具有所有给定列表字符的字符串

给定字符串列表和字符列表,提取所有字符串,包含字符列表中的所有字符。

方法#1:使用循环

在此,我们迭代列表中的所有元素,并检查是否所有元素都存在于特定的字符串中,如果是,则将该字符串附加到结果中。

Python3
# Python3 code to demonstrate working of 
# Strings with all List characters
# Using loop
  
# initializing list
test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing char_list 
chr_list = ['g', 'f']
  
res_list = []
for sub in test_list:
    res = True 
    for ele in chr_list:
          
        # check if any element is not present
        if ele not in sub:
            res = False 
            break
    if res:
        res_list.append(sub)
  
# printing results
print("Filtered Strings : " + str(res_list))


Python3
# Python3 code to demonstrate working of 
# Strings with all List characters
# Using all() + list comprehension
  
# initializing list
test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing char_list 
chr_list = ['g', 'f']
  
# using all() to check containment of all characters
res_list = [sub for sub in test_list if all(ele in sub for ele in chr_list)]
  
# printing results
print("Filtered Strings : " + str(res_list))


输出
The original list is : ['Geeks', 'Gfg', 'Geeksforgeeks', 'free']
Filtered Strings : ['Gfg', 'Geeksforgeeks']

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

在此,我们使用 all() 检查所有字符是否存在,如果检查出来,则将 String 附加到结果中。迭代部分在列表理解中作为单行完成。

Python3

# Python3 code to demonstrate working of 
# Strings with all List characters
# Using all() + list comprehension
  
# initializing list
test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing char_list 
chr_list = ['g', 'f']
  
# using all() to check containment of all characters
res_list = [sub for sub in test_list if all(ele in sub for ele in chr_list)]
  
# printing results
print("Filtered Strings : " + str(res_list))
输出
The original list is : ['Geeks', 'Gfg', 'Geeksforgeeks', 'free']
Filtered Strings : ['Gfg', 'Geeksforgeeks']