gpt4 book ai didi

python - 如何计算一个序列在 python 中的给定字符串中出现了多少次?

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:13 25 4
gpt4 key购买 nike

我正在尝试计算一个序列在给定字符串中出现的次数。

def count_seqence(str, seq):
count = 0
if seq in str:
count += 1
return count
print(count_seqence("the quick brown fox jumps over the lazy dog","he"))

但这只运行一次并且不循环,我如何循环并计算出现的次数,因为我知道循环将针对每个字符而不是序列,这让我感到困惑。

最佳答案

既然你使用了 if ,而不是在循环中,这意味着条件是 True ,因此你递增 count ,或者它是 False在这种情况下,您不会执行主体。

如果你想数数,你需要一些“循环”机制。这不必是明确的,例如 in也隐藏了一个循环。但这只会导致 TrueFalse .

非重叠( count_seqence('aaaa', 'aa')2 )

对于非重叠计数,我们可以使用 str.count :

def count_seqence(text, seq):
return text.count(seq)

在这种情况下,定义一个特定的函数当然是毫无用处的。请注意,以上内容只会计算非重叠 匹配项。例如,当您计算 'aa' 时在'aaaa'你会得到2 , 不是 3 .

重叠( count_seqence('aaaa', 'aa')3 )

对于重叠,我们需要执行 str.find ,并更新“搜索窗口”,直到我们不再找到匹配项,例如:

def count_seqence(text, seq):
cnt = 0
idx = text.find(seq)
while idx >= 0:
cnt += 1
idx = text.find(seq, idx+1)
return cnt

因此我们有一个 idx存储新匹配发生的索引,每次 idx大于或等于 0 (我们找到了一个匹配项),我们递增 cnt , 并更改 idx下一场比赛。

关于python - 如何计算一个序列在 python 中的给定字符串中出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com