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

2024-06-16 13:49:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个输入:BFFBFBFBFBBBBF。 我想数到B,答案应该是6。(忽略重复的)

如何在python中实现它?你知道吗


Tags: 答案bffbfbfbfbbbbf
3条回答

使用^{}

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

编辑:另外,为了更广泛地使用,最好使用^{}来获得所有字符的count。你知道吗

>>> from collections import Counter
>>> Counter(l)
=> Counter({'B': 6, 'F': 6})
s = "BFFBFBFFFBFBBBFBBBBFF"
f = False
count = 0
for i in s:
    if f and i == 'B':
        continue
    elif i == 'B':
        count += 1
        f = True
    else:
        f = False
print(count)

另一个

from itertools import groupby
count = 0
for i,_ in groupby(s):
    if i == 'B':
        count += 1
print(count)

您应该设置一个计数器和一个标志变量。然后只计算不重复的事件,并翻转标志。逻辑很简单:如果当前字母是“B”,而前面的字母不是“B”(dup=False),则将其计数并翻转布尔值:

s = 'BFFBFBFFFBFBBBFBBBBFF'

count = 0
dup = False
for l in s:
    if l == 'B' and not dup:
        count += 1
        dup = True
    elif l != 'B':
        dup = False

# count: 6

相关问题 更多 >