【发布时间】:2015-12-01 13:34:13
【问题描述】:
我正在尝试在下面的字符串中计算字母的“l”和“o”。 如果我数一个字母,它似乎有效,但只要我数下一个字母“o”,字符串就不会添加到总数中。我错过了什么?
s = "hello world"
print s.count('l' and 'o')
输出:5
【问题讨论】:
我正在尝试在下面的字符串中计算字母的“l”和“o”。 如果我数一个字母,它似乎有效,但只要我数下一个字母“o”,字符串就不会添加到总数中。我错过了什么?
s = "hello world"
print s.count('l' and 'o')
输出:5
【问题讨论】:
统计s中的所有字母:
answer = {i: s.count(i) for i in s}
然后对来自s 的所有键(字母)求和:
print(answer['l'] + answer['o'])
【讨论】:
O(n^2),其中n 是字符串长度,而不是other answer 使用Counter...
使用正则表达式:
>>> import re
>>> len(re.findall('[lo]', "hello world"))
5
或map:
>>> sum(map(s.count, ['l','o']))
5
【讨论】:
你的意思可能是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
【讨论】:
count 计算非重叠匹配。 See here.
另外,由于您要计算给定字符串中多个字母的出现次数,请使用collections.Counter:
>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5
请注意,您当前使用的s.count('l' and 'o') would evaluate 为s.count('o'):
表达式
x and y首先计算x:如果x为假,则其值为 回来;否则,y被评估,结果值为 返回。
换句话说:
>>> 'l' and 'o'
'o'
【讨论】: