【问题标题】:python text.count do no return the correct number of occurences [duplicate]python text.count不返回正确的出现次数[重复]
【发布时间】:2017-06-09 08:38:49
【问题描述】:

我对 python 中的 text.count() 函数有疑问。 假设我有以下文本,我想返回“CCC”的出现次数:

text = "ACCCGTTGCCCC"
print text.count("CCC")

为什么它返回 2 而不是 3?

【问题讨论】:

标签: python text


【解决方案1】:

根据str.count方法的文档:

>>> help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are interpreted
    as in slice notation.

因此,在您的情况下,CCC 在字符串 "ACCCGTTGCCCC" 中有两个不重叠的出现。

希望对你有帮助。

【讨论】:

  • 谢谢,如果字符串重叠,我应该实现自己的功能还是有一些内置的功能?
  • @simalps 你可以使用集合中的计数器,它会输出一个频率字典
【解决方案2】:
Text.count() 

返回子字符串 sub 的出现次数。 在这种情况下:“ACCCGTTGCCCC” 给你 2,因为你的子字符串是“CCC”,它在字符串中只出现两次。(即“C”彼此相邻放置至少 3 次。)

【讨论】:

    【解决方案3】:

    最好使用已经可用的Counter

    from collections import Counter
    
    c = Counter('test')
    print (c)
    >>> Counter({'t': 2, 'e': 1, 's': 1})
    

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 2011-06-09
      • 2021-09-26
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2012-10-16
      相关资源
      最近更新 更多