Python – 提取子字符串匹配的索引
给定一个字符串列表和一个子字符串,提取字符串的索引列表,其中出现该子字符串。
Input : test_list = [“Gfg is good”, “for Geeks”, “I love Gfg”, “Gfg is useful”], K = “Gfg”
Output : [0, 2, 3]
Explanation : “Gfg” is present in 0th, 2nd and 3rd element as substring.
Input : test_list = [“Gfg is good”, “for Geeks”, “I love Gfg”, “Gfg is useful”], K = “good”
Output : [0]
Explanation : “good” is present in 0th substring.
方法 #2:使用循环 + enumerate()
这是可以完成此任务的粗暴方式。在此,我们使用 enumerate() 迭代所有元素及其索引,并使用条件语句来获得所需的结果。
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using loop + enumerate()
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate through list
res = []
for idx, ele in enumerate(test_list):
if K in ele:
res.append(idx)
# printing result
print("The indices list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using list comprehension + enumerate()
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using list comprehension and enumerate to offer compact solution
res = [idx for idx, val in enumerate(test_list) if K in val]
# printing result
print("The indices list : " + str(res))
输出
The original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]
方法 #2:使用列表理解 + enumerate()
这是可以解决此任务的另一种方式。在此,我们使用列表理解执行与上述方法类似的任务,并使用 enumerate() 来获得紧凑的解决方案。
Python3
# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using list comprehension + enumerate()
# initializing list
test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"]
# initializing K
K = "Gfg"
# printing original list
print("The original list : " + str(test_list))
# using list comprehension and enumerate to offer compact solution
res = [idx for idx, val in enumerate(test_list) if K in val]
# printing result
print("The indices list : " + str(res))
输出
The original list : ['Gfg is good', 'for Geeks', 'I love Gfg', 'Its useful']
The indices list : [0, 2]