[英]How to find all occurrences of a list of strings in a string and return a list of list of int in python?
例如
def find_all_occurrences(a,b):
'''
>>>find_all_occurrences('wswwswwwswwwws', ['ws', 'wws'])
[[0,3,7,12], [2,6,11]]
'''
如何在不導入任何模塊的情況下返回包含所有出現的列表的列表。
您可以使用正則表達式
import re
def all_occurrences(a, b):
return [[occur.start() for occur in re.finditer(word, a)] for word in b]
沒有進口,情況會有些混亂,但絕對可行
def all_occurrences(a, b):
result = []
for word in b:
word_res = []
index = a.find(word)
while index != -1:
word_res.append(index)
index = a.find(word, index+1)
result.append(word_res)
return result
您可以通過使用上一個找到的位置作為下一個搜索的開始來查找所有出現的事件:
str.find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
重復調用haystack.find(needle, last_pos + 1)
直到返回-1的循環應該起作用。
您還可以通過簡單的列表理解來解決此類問題
[[i for i in range(len(a)-len(strng)+1) if strng == a[i:i+len(strng)]] for strng in b]
哪里
>>> a
'wswwswwwswwwws'
>>> b
['ws', 'wws']
遞歸過程的解決方案。 我使用了一個嵌套/內部函數來維護OP的函數簽名:
def find_all_occurrences(a,b):
'''
>>>find_all_occurrences('wswwswwwswwwws', ['ws', 'wws'])
[[0,3,7,12], [2,6,11]]
'''
def r(a, b, count = 0, result = None):
if not a:
return result
if result is None:
# one sublist for each item in b
result = [[] for _ in b]
for i, thing in enumerate(b):
if a.startswith(thing):
result[i].append(count)
return r(a[1:], b, count = count + 1, result = result)
return r(a, b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.