使用while循环计算列表中的元素

时间:2013-10-14 12:03:55

标签: python while-loop

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)后再添加一个并添加一个并在Sochi之后停止,或者在列表的第一个元素处添加一个,一旦到达索契就停下来。

1 个答案:

答案 0 :(得分: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,因此该行基本上取第一个元素 然后,在循环内,count递增,下一个元素从列表中取出 当地点等于“索契”时,迭代停止,这意味着不会检查“索契”和随后的任何元素。

这真令人困惑,而且写得很糟糕。这是一个更简单的版本

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