2013-10-09 78 views
0

此代碼可以正常工作,但我不能100%確定它是如何工作的,因爲它在我借用的Python書中。我不明白程序如何檢查是否有多字。還什麼做帶星線意味着檢測列表中的元素是否是多字

places= ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center", "LA Dodgers stadium", "Home"] 
def placesCount(places): 
    multi_word = 0 
    count = 0 
    **while True: 
     place = places[count]** 
     if place == 'LA Dodgers stadium': 
      break 
     **if ' ' in place:** 
      multi_word += 1 
     count += 1 
    return count + 1, multi_word + 1 

placesCount(places) 

回答

1

的方法檢查列表places一個字符串中有空格,它認爲,一個多字。

如果列表places包含字符串LA Dodgers stadium,該方法將返回字符串的位置,加上在其之前找到多少個多個單詞的計數。

這是一個提示:當你將['LA Dodgers stadium']傳遞給函數時會發生什麼?它會返回正確的數字嗎?

def placesCount(places): 
    multi_word = 0 # a count of how many multiple words were found 
    count = 0 # an initializer (not needed in Python) 
    while True: # start a while loop 
     place = places[count] # get the object from the places list 
           # at position count 
     if place == 'LA Dodgers stadium': 
      # quit the loop if the current place equals 'LA Dodgers stadium' 
      break 
     if ' ' in place: 
      # If the current string from the places list 
      # (which is stored pointed to by the name place) 
      # contains a space, add one to the value of multi_word 
      multi_word += 1 
     # Add one to count, so the loop will pick the next object from the list 
     count += 1 
    # return a tuple, the first is how many words in the list 
    # and the second item is how many multiple words (words with spaces) 
    return count + 1, multi_word + 1 
到位
+0

如果「」: #如果到位的字符串包含空格,加一個我不明白它是如何檢測是否有空間 – user2821664

+0

別提我的錯誤的空間在一側的報價價值 – user2821664

+0

是它的任何方式如何找到空間而不使用find方法。我需要在不使用查找方法的情況下完成我的程序 – user2821664

相關問題