【问题标题】:Count a group of same character in python [duplicate]在python中计算一组相同的字符[重复]
【发布时间】:2020-11-30 22:45:51
【问题描述】:

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

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 

【问题讨论】:

  • 尝试使用"B" 而不是B
  • 我试过不行

标签: python line-count


【解决方案1】:

这是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]

【讨论】:

  • 谢谢。它成功了
【解决方案2】:

试试这个:

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

>>>print(counts)
 
[3, 11, 1]

【讨论】:

  • 一个很好的解决方案,而且非常“pythonic”,但是对于学习的人来说,添加一个关于它是如何工作的描述会很好。
  • i 在此示例中未定义。看起来您正在计算文件每一行中 B 的数量,而不是单行中的 B 组。
【解决方案3】:

看起来很简单。

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

【讨论】:

  • 请解释您所做的更改以及您的代码是如何工作的。
猜你喜欢
  • 1970-01-01
  • 2019-02-17
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2020-02-08
  • 2015-09-28
相关资源
最近更新 更多