gpt4 book ai didi

python - 计算忽略重复的特定字符数 : Python

转载 作者:行者123 更新时间:2023-11-28 21:03:09 24 4
gpt4 key购买 nike

我有这样的输入:BFFBFBFFFBFBBBFBBBBFF。我想数“B”,答案应该是 6。(忽略重复的)

如何在 python 中实现?

最佳答案

使用itertools.groupby :

>>> from itertools import groupby
>>> l = [k for k,v in groupby(s)]

>>> l
=> ['B', 'F', 'B', 'F', 'B', 'F', 'B', 'F', 'B', 'F', 'B', 'F']

>>> l.count('B')
=> 6

#驱动程序值:

IN : s = 'BFFBFBFFFBFBBBFBBBBFF

编辑:此外,为了更广泛的使用,最好使用 collections.Counter获取所有字符的计数

>>> from collections import Counter
>>> Counter(l)
=> Counter({'B': 6, 'F': 6})

关于python - 计算忽略重复的特定字符数 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871579/

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