尝试仅使用while循环计算字母出现的次数

时间:2014-09-18 20:01:48

标签: python python-2.7

我正在计算原始输入'短语'中有多少o并计算第一个o并表示已经完成但是之后有很多o。我如何通过no for循环来计算所有的o。

while loop_count<len(phrase):
    if "o" in phrase:
        loop_count += 1
        count2 += 1
      if loop_count>len(phrase):
          print loop_count
          break
      else:
          continue
  else:
    print loop_count
    continue

4 个答案:

答案 0 :(得分:2)

您可以将sum与迭代器一起使用(在本例中为generator expression):

>>> sum(c=='o' for c in 'oompa loompa')
4

你可以使用带有len的正则表达式:

>>> re.findall('o', 'oompa loompa')
['o', 'o', 'o', 'o']
>>> len(re.findall('o', 'oompa loompa'))
4

您可以使用计数器:

>>> from collections import Counter
>>> Counter('oompa loompa')['o']
4

或者只使用字符串的'count'方法:

>>> 'oompa loompa'.count('o')
4

如果您确实希望使用while循环,请使用pop方法将列表作为堆栈使用:

s='oompa loompa'
tgt=list(s)
count=0
while tgt:
    if tgt.pop()=='o':
        count+=1

或'for'循环 - 更多Pythonic:

count=0        
for c in s:
    if c=='o':
        count+=1 

答案 1 :(得分:2)

您可以使用count功能:

phrase.count('o')

但是如果你想在'o'的一个匹配之后发送一条消息,对于所有字符串的跳过循环,只需使用'in',如下所示:

if 'o' in phrase :
 # show your message ex: print('this is false')

答案 2 :(得分:1)

让我们尝试剖析您了解正在发生的事情的代码。看我的评论

while loop_count<len(phrase):
    if "o" in phrase: # See comment 1
        loop_count += 1 # Why are you incrementing both of these?
        count2 += 1
      if loop_count>len(phrase): # What is this statement for? It should never happen.
                ## A loop always exits once the condition at the while line is false
                ## It seems like you are manually trying to control your loop
                ##  Which you dont need to do
          print loop_count
          break # What does this accomplish?
      else:
          continue
  else:
    print loop_count
    continue # Pointless as we are already at end of loop. Consider removing

评论1:您在询问是否有&#39; o&#39;在这个短语中的任何地方。你想要询问当前的字母是否是o。也许您打算使用索引访问短语的字母,例如if 'o' == phrase[loop_count]。如果你这样做,你想每次都增加loop_count,但只有在字母是o时才算数。

您可以像这样重写:

loop_count, o_count = 0, 0
while loop_count<len(phrase):
    # loop_count represents how many times we have looped so far
    if "o" == phrase[loop_count].lower(): # We ask if the current letter is 'o'
        o_count += 1 # If it is an 'o', increment count
    loop_count += 1 # Increment this every time, it tracks our loop count

print o_count

答案 3 :(得分:0)

使用理解

len([i for i in phrase if i=="o"])