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]) 做了什么,也不明白为什么我需要它两次。

它是让程序从 Jack 开始,然后在到达列表的下一个元素 (Jo hn) 时添加 1,然后再添加一个并在 Sochi 之后停止,还是在列表的第一个元素添加一个,然后停止一旦到达索契。

4

1 回答 1

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]

第一次 count 等于 0,因此 line 基本上取第一个元素,然后在循环中,count 递增,下一个元素从列表中取出,当 place 等于“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     
于 2013-10-14T12:22:52.167 回答