[英]How to find all occurrences of a list of strings in a string and return a list of list of int in python?
For example 例如
def find_all_occurrences(a,b):
'''
>>>find_all_occurrences('wswwswwwswwwws', ['ws', 'wws'])
[[0,3,7,12], [2,6,11]]
'''
How can I return a list of lists that have all the occurrences without import any modules. 如何在不导入任何模块的情况下返回包含所有出现的列表的列表。
You can use regular expressions 您可以使用正则表达式
import re
def all_occurrences(a, b):
return [[occur.start() for occur in re.finditer(word, a)] for word in b]
Without imports it gets a little messy, but definitely still doable 没有进口,情况会有些混乱,但绝对可行
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
You can find all the occurrences by using the last found position as the start of the next search: 您可以通过使用上一个找到的位置作为下一个搜索的开始来查找所有出现的事件:
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.
A loop that calls haystack.find(needle, last_pos + 1)
repeatedly until it returns -1 should work. 重复调用
haystack.find(needle, last_pos + 1)
直到返回-1的循环应该起作用。
you can also have simple list comprehensions to help with problems like these 您还可以通过简单的列表理解来解决此类问题
[[i for i in range(len(a)-len(strng)+1) if strng == a[i:i+len(strng)]] for strng in b]
where 哪里
>>> a
'wswwswwwswwwws'
>>> b
['ws', 'wws']
Solution with a recursive procedure. 递归过程的解决方案。 I used a nested/inner function to maintain the OP's function signature:
我使用了一个嵌套/内部函数来维护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.