我有子字符串列表,我正在检查是否在另一个字符串中找到了任何子字符串。 any确实返回布尔值。
>>> list=['oh' , 'mn' , 'nz' , 'ne']
>>> name='hstntxne'
>>> any(x in name for x in list)
True
>>> name='hstnzne'
>>> any(x in name for x in list)
True
我想要返回索引。例如,它应该是第一次,第二次应该是2和3.
答案 0 :(得分:0)
您可以使用内置的enumerate()
功能。
def get_index(name, lis=['oh' , 'mn' , 'nz' , 'ne']):
indx = []
for index, element in enumerate(lis):
if element in name:
indx.append(index)
return indx
现在get_index(name='hstnzne')
会给[2, 3]
和get_index(name='hstntxne')
会给[3]
答案 1 :(得分:0)
首先,请勿拨打您的列表list
。 list
是一个python数据结构,除非您有特定的理由,否则您不希望覆盖该名称。
您可以通过一行中的列表理解轻松实现此目的。
substrings = ['oh' , 'mn' , 'nz' , 'ne']
name1='hstntxne'
name2='hstnzne'
[substrings.index(x) for x in substrings if x in name1]
这将返回3
[substrings.index(x) for x in substrings if x in name2]
返回[2,3]
为了使这个工作与任何子串列表一起使用,名称将它放在一个函数中:
def getIndex(subs, name):
return [subs.index(x) for x in subs if x in name]
getIndex(substrings, name2) #example call
答案 2 :(得分:0)
import re
# Try and use regex to see if subpattern exists
l = ['oh', 'mn', 'nz', 'ne']
name='hstnzne'
match_indx = []
for i, sub_str in enumerate(l):
result = re.split(sub_str, name)
if (len(result)>1):
# We could split our string due to match, so add index of substring
match_indx.append(i)
print(match_indx)