Python – 字符串列表中存在子字符串
给定子字符串列表和字符串列表,检查每个子字符串是否存在于列表中的任何字符串中。
Input : test_list1 = [“Gfg”, “is”, “best”], test_list2 = [“I love Gfg”, “Its Best for Geeks”, “Gfg means CS”]
Output : [True, False, False]
Explanation : Only Gfg is present as substring in any of list String in 2nd list.
Input : test_list1 = [“Gfg”, “is”, “best”], test_list2 = [“I love Gfg”, “It is Best for Geeks”, “Gfg means CS”]
Output : [True, True, False]
Explanation : Only Gfg and is are present as substring in any of list String in 2nd list.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们为,列表中的每个元素检查它是否是任何其他列表元素的子字符串。
Python3
# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using loop
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using loop to iterate
res = []
for ele in test_list1 :
temp = False
# inner loop to check for
# presence of element in any list
for sub in test_list2 :
if ele in sub:
temp = True
break
res.append(temp)
# printing result
print("The match list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using list comprehension + any()
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# any() reduces a nesting
# checks for element presence in all Substrings
res = [True if any(i in j for j in test_list2) else False for i in test_list1]
# printing result
print("The match list : " + str(res))
输出
The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : ['I love Gfg', 'Its Best for Geeks', 'Gfg means CS']
The match list : [True, False, True]
方法 #2:使用列表理解 + any()
上述功能的组合可以用来解决这个问题。在此,我们使用 any() 检查任何子列表,并使用列表推导来执行迭代。
Python3
# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using list comprehension + any()
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# any() reduces a nesting
# checks for element presence in all Substrings
res = [True if any(i in j for j in test_list2) else False for i in test_list1]
# printing result
print("The match list : " + str(res))
输出
The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : ['I love Gfg', 'Its Best for Geeks', 'Gfg means CS']
The match list : [True, False, True]