【问题标题】:Count multiple letters in string Python计算字符串Python中的多个字母
【发布时间】:2015-12-01 13:34:13
【问题描述】:

我正在尝试在下面的字符串中计算字母的“l”和“o”。 如果我数一个字母,它似乎有效,但只要我数下一个字母“o”,字符串就不会添加到总数中。我错过了什么?

s = "hello world"

print s.count('l' and 'o')

输出:5

【问题讨论】:

    标签: python string count


    【解决方案1】:

    统计s中的所有字母:

    answer = {i: s.count(i) for i in s}
    

    然后对来自s 的所有键(字母)求和:

    print(answer['l'] + answer['o'])
    

    【讨论】:

    • 这基本上是O(n^2),其中n 是字符串长度,而不是other answer 使用Counter...
    【解决方案2】:

    使用正则表达式:

    >>> import re
    >>> len(re.findall('[lo]', "hello world"))
    5
    

    map:

    >>> sum(map(s.count, ['l','o']))
    5
    

    【讨论】:

    • 虽然这些方法产生了所需的结果,但是如果字符串很大(比如10000个字符),这两种方法都会以秒为单位花费时间,有什么有效的方法吗?
    【解决方案3】:

    你的意思可能是s.count('l') + s.count('o')

    您粘贴的代码等于s.count('o')and 运算符检查其第一个操作数(在本例中为 l)是否为 false。如果为 false,则返回其第一个操作数 (l),但不是,因此返回第二个操作数 (o)。

    >>> True and True
    True
    >>> True and False
    False
    >>> False and True
    False
    >>> True and 'x'
    'x'
    >>> False and 'x'
    False
    >>> 'x' and True
    True
    >>> 'x' and False
    False
    >>> 'x' and 'y'
    'y'
    >>> 'l' and 'o'
    'o'
    >>> s.count('l' and 'o')
    2
    >>> s.count('o')
    2
    >>> s.count('l') + s.count('o')
    5
    

    Official documentation

    【讨论】:

    • 字符串的情况下:s = 'azcbobobegghakl' 如果我想知道bob出现的次数。我该怎么做。正确的输出是 2。@Wander Nauta
    • @taji01这是一个完全不同的问题,尤其是因为您似乎正在寻找 重叠 匹配项。 count 计算非重叠匹配。 See here.
    【解决方案4】:

    另外,由于您要计算给定字符串中多个字母的出现次数,请使用collections.Counter

    >>> from collections import Counter
    >>>
    >>> s = "hello world"
    >>> c = Counter(s)
    >>> c["l"] + c["o"]
    5
    

    请注意,您当前使用的s.count('l' and 'o') would evaluates.count('o')

    表达式x and y 首先计算x:如果x 为假,则其值为 回来;否则,y 被评估,结果值为 返回。

    换句话说:

    >>> 'l' and 'o'
    'o'
    

    【讨论】:

    • 字符串的情况下:s = 'azcbobobegghakl' 如果我想知道bob出现的次数。我该怎么做。正确的输出是 2。@alecxe
    猜你喜欢
    • 2016-07-25
    • 2014-07-17
    • 2012-01-11
    • 2019-11-03
    • 2016-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多