3 回答

TA貢獻1856條經驗 獲得超17個贊
如果字母總是連續的,這將起作用:
wd = "stackoverflow"
lst = ["".join(wd[i:i+5]) for i in range(len(wd)-4)]
print(lst)
輸出
['stack', 'tacko', 'ackov', 'ckove', 'kover', 'overf', 'verfl', 'erflo', 'rflow']

TA貢獻2080條經驗 獲得超4個贊
我想你可以只使用一個簡單的循環和一個大小為 5 的滑動窗口
word = "stackoverflow"
result=[]
for i in range(len(word)-5):
result.append(word[i:i+5])
print(result)
這是非常有效的,因為它在 O(n) 線性時間上運行

TA貢獻1824條經驗 獲得超6個贊
因為正如我在 findall 文檔字符串中看到的那樣,它返回所有非重疊匹配項:
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
查看主題中沒有使用正則表達式的解決方案。
添加回答
舉報