我试图获取字符串中键的所有索引并将它们存储在字典中,以便 每个索引都有一个映射到它的键列表。
示例:
string = "loloo and foofoo at the foo bar"
keys = "foo", "loo", "bar", "lo"
我期望类似的东西
{
0: [lo]
2: [loo, lo]
10: [foo]
13: [foo]
24: [foo]
28: [bar]
}
我当前的答案如下:
def get_index_for_string(string, keys):
"""
Get all indexes of the keys in the string and store them in a dict, so that
every index has a list of keys mapping to it.
"""
key_in_string = dict((key, [m.start() for m in re.finditer(key, string)])
for key in keys if key in string)
index_of_keys = {}
for key, values in key_in_string.items():
for value in values:
if not value in index_of_keys:
index_of_keys[value] = []
index_of_keys[value].append(key)
return index_of_keys
关于如何做得更好有什么建议吗?
最佳答案
非正则表达式
方法:
使用str.find()
,str.find()
接受一个可选的第二个参数,它是您要在其后查找单词的索引。
def indexes(word,strs):
ind=0 #base index is 0
res=[]
while strs.find(word,ind)!=-1: #loop until str.find() doesn't return -1
ans=strs.find(word,ind)
res.append(ans)
ind=ans+1 #change base index if the word is found
return res
strs = "loloo and foofoo at the foo bar"
keys = ["foo", "loo", "bar", "lo"]
print {x:indexes(x,strs) for x in keys}
输出:
{'lo': [0, 2], 'foo': [10, 13, 24], 'bar': [28], 'loo': [2]}
关于python - 将键(全部出现在给定字符串中)映射到字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554422/