[英]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.