繁体   English   中英

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

[英]Trying to count the number of times a letter appears using only a while loop

我试图计算原始输入“短语”中有多少个o,它计算第一个o并说完成了,但是之后有许多o。 如何获取没有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

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

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

您可以使用count功能:

phrase.count('o')

但是,如果您想在匹配整个字符串后使用“ o”匹配跳过循环后发送消息,则使用“ in”,如下所示:

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

让我们尝试剖析您的代码,您了解发生了什么。 查看我的评论

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:您要询问短语中是否有“ o”。 相反,您想询问当前字母是否为o。 也许您想访问带有索引的短语的LETTER,例如if 'o' == phrase[loop_count] 如果执行此操作,则每次都希望增加loop_count,但仅当字母为o时,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

使用理解

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM