2016-11-01 25 views

回答

0

您可以通過使用最後發現作爲下一個搜索的開始找到所有出現:

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應該工作。

2

您可以使用正則表達式

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 
+0

OP請求沒有進口。 – wwii

+0

@wwii註明。編輯製作 –

+0

我測試它,並在第5行說,TypeError:不能將'list'對象隱式轉換爲str –

0

你也可以有簡單的列表解析來幫助這樣的

問題
[[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'] 
0

帶遞歸過程的解決方案。我用了一個嵌套/內功能保持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) 
相關問題