2014-09-18 64 views
2

我想要計算在原始輸入「短語」中有多少個o,並且它計數第一個o並且說它已完成但是有很多o之後。我如何得到它所有的O沒有for循環。試圖用只有一個while循環來計算一個字母出現的次數

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 

回答

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:你問,如果一個「O」是一語中的任何地方。你反而想問問當前的信是否是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 
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 

或者只是使用字符串的「計數」方法:

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

如果你真的使用while循環,使用列表與pop方法棧:

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

或者 'for' 循環 - 更Python:

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

您可以使用count功能:

phrase.count('o') 

,但如果你想要跳過遍歷所有字符串的「O」的一場比賽後,發送郵件,只要用「中」是這樣的:

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

使用內涵

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