2

我有一个这样的输入文件:

CCCCCCCCCCCCCBBBCCBBBBBBBBBBBCCCCCCCCCCCCCCCCBCCC

我想计算每组有多少个“B”。所以输出将是:

B: 3, 11, 1

我尝试了两个不同的脚本,但都给出了 B = 15 的总数。

这是我的尝试之一:

import collections

with open('input.txt') as infile:  
    counts = collections.Counter(B.strip() for B in infile)  
for line, count in counts.most_common():  
    print line, count 
4

3 回答 3

2

这是一个很好的应用程序,itertools.groupby它将类似值的输入分组到子迭代器中。

>>> import itertools
>>> text="CCCCCCCCCCCCCBBBCCBBBBBBBBBBBCCCCCCCCCCCCCCCCBCCC"
>>> b_counts = []
>>> for letter, repeats in itertools.groupby(text):
...     if letter == "B":
...             b_counts.append(len(list(repeats)))
... 
>>> b_counts
[3, 11, 1]
于 2020-11-30T22:56:08.370 回答
1

试试这个:

with open('input.txt') as infile:  
    counts = [i.count('B') for i in infile]

>>>print(counts)
 
[3, 11, 1]
于 2020-11-30T22:54:07.280 回答
0

看起来很简单。

def countBGroups(S):

    groups = []
    c = 0

    for s in S:

        if s == "B":
            c += 1
        else:
            if c != 0:
                groups.append(c)
            
            c = 0
    
    if c != 0:
        groups.append(c)
    
    return groups

with open("input.txt") as f:

    print(countBGroups(f.read()))
于 2020-11-30T22:56:25.027 回答