2013-10-09 47 views
0
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 ' ' in place and place!='LA Dodgers stadium' **""" or anything that comes after LA dogers stadium"""** : 
      multi_word += 1 
     if '' in place and place!='LA Dodgers stadium' """ **or anything that comes after LA dogers stadium**""": 
      count += 1 
    print (count, "places to LA dodgers stadium"), print (multi_word) 
placesCount(places) 

列表中的某個元素我基本上想知道我怎麼可以添加到列表停止while循環,當它到達列表("LA Dodgers Stadium")的某個元素while循環這個案例。在它到達列表中的元素後,它不應該添加任何內容。停止當達到

+9

這是行不通的嗎? –

+4

使用'放置在地方:'循環你的地方,而不是while-thingie;那麼你不需要任何特殊的空白處理。另外爲什麼不是一個簡單的'len(places)'? –

回答

0
place = None 
while place != 'stop condition': 
    do_stuff() 
1

此代碼似乎工作得很好。我打印出了placesCount的結果,這是(6,5)。看起來這意味着功能打了6個單詞,其中5個是多個單詞。這符合你的數據。

正如弗雷德裏克所說的,在place循環中使用place將是實現你想要做的事情的一種更漂亮的方式。

+0

如何打印結果? print(placesCount)不起作用 – user2821664

+0

如果你的函數返回任何類型的數據(如數字,列表等),你應該能夠打印placesCount(places)。 – Oniofchaos

3

您的代碼似乎工作。這裏有一個稍微好一點的版本:

def placesCount(places): 
    count = 0 
    multi_word = 0 
    for place in places: 
     count += 1 
     if ' ' in place: 
      multi_word += 1 
     if place == 'LA Dodgers stadium': 
      break 
    return count, multi_word 

或者用itertools

from itertools import takewhile, ifilter 

def placesCount(places): 
    # Get list of places up to 'LA Dodgers stadium' 
    places = list(takewhile(lambda x: x != 'LA Dodgers stadium', places)) 

    # And from those get a list of only those that include a space 
    multi_places = list(ifilter(lambda x: ' ' in x, places)) 

    # Return their length 
    return len(places), len(multi_places) 

的你怎麼可以再使用的功能(即沒有從原來的例子BTW改變,功能還是一個例子表現相同 - 接受地點列表並返回包含兩個計數的元組):

places = ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center", "LA Dodgers stadium", "Home"] 

# Run the function and save the results 
count_all, count_with_spaces = placesCount(places) 

# Print out the results 
print "There are %d places" % count_all 
print "There are %d places with spaces" % count_with_spaces 
+0

這可能是OP後面的內容,+1 –

+0

如何打印結果? print(placesCount)不起作用 – user2821664

+0

我用示例更新了我的帖子。 –