2013-10-14 29 views
0
places = [ "Jack", "Jo hn", "Sochi", "Manan", "Mayank"] 
count=0 
multi_word=0 
place = places[count] 
while place != "Sochi" : 
    if ' ' in place: 
     multi_word += 1 

    count += 1 
    place = places[count] 

print ('Number of cities before Sochi:', count) 
print ('Number of multiple names cities before Sochi:', multi_word) 

這是我的代碼我不明白這一行(place = places [count])是幹什麼的,我也不明白爲什麼我需要它兩次。使用while循環計算列表中的元素

它是否使程序從Jack開始,然後在到達列表的下一個元素(Jo hn)時添加1,並且在Sochi之後再添加一個並停止,或者在第一個元素處添加一個列表,然後停止一旦到達索契。

+0

你真的需要'while'循環? – alexvassel

+0

要訪問列表中的項目,您需要'places [count]',但這也可以使用for循環完成。 –

+0

這是一個不同的問題 – user2821664

回答

0

你的算法可表示爲如下:

places = [ "Jack", "Jo hn", "Sochi", "Manan", "Mayank"] 
#Set the number of multiword to 0 
multi_word=0 
#Take the first element from the list as place 
count=0 
place = places[count] 
#If place is "Sochi" we're done 
while place != "Sochi" : 
    #Check if place is a multiword 
    if ' ' in place: 
     multi_word += 1 
    #Move to the next element 
    count += 1 
    place = places[count] 

第一次計數等於0,使得線基本上採取第一元件 然後,在循環內,計數遞增,並且下一個元素是取自列表 當地點等於「Sochi」時,迭代停止,這意味着「Sochi」和任何後面的元素都不會被檢查。

這真是令人困惑和寫得不好。這裏有一個更簡單的版本

place_list = [ "Jack", "Jo hn", "Sochi", "Manan", "Mayank"] 
multi_word_count = 0 
place_index = 0 
while True: 
    current_place = place_list[index] 
    if current_place == "Sochi": 
     break 
    if ' ' in current_place: 
     multi_word_count += 1 
    place_index += 1 

現在,這裏是一個更好的解決方案

place_list = [ "Jack", "Jo hn", "Sochi", "Manan", "Mayank"] 
multi_word_count = 0 

for place in place_list: 
    if place == "Sochi": 
     break 
    if ' ' in current_place: 
     multi_word_count += 1  
+0

'place_index'似乎已經消失在最後一個例子中... –

+0

@JonClements是的,因爲它根本就不需要:) 如果你想要在「索契」之前的元素數量,只需做一個place_list.index(「索契「) –

+0

ahh ...好吧 - 以爲你一次性嘗試完成所有事情......所以我想你可以在itertools.takewhile('Sochi'.__ ne__ ,place_list))' –