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

时间:2013-10-14 11:23:56

标签: python while-loop

places = ["Jack", "John", "Sochi"]
count=0
multi_word=0
place  = places[count]
while place != "Sochi" and count < len(places):
    if ' ' in place:
        multi_word += 1

    count += 1
    place = places[count]

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

我的代码应该打印索契之前的城市数量,不包括索契。我不明白这一行(place = places [count])是做什么的,我也不明白为什么我需要它两次。

4 个答案:

答案 0 :(得分:2)

foreach会把它搞砸了

places = ["Jack", "John", "Sochi"]
count = 0
for place in places:
    if ' ' in place:
        multi_word += 1
    if place == "Sochi":
        break
    count += 1

答案 1 :(得分:1)

count=0
place = places[count]

现在place总是places[0],即杰克。因此,while循环仅终止于第二个条件,为您提供列表长度为3。

place = places[count]应该进入循环。

答案 2 :(得分:1)

您可以使用以下while循环来检查索契之前的地点数量:

places = ["Jack", "John", "Sochi"]
count = 0
multi_word = 0
while count < len(places):
    place = places[count]
    if ' ' in place:
        multi_word += 1
    if place == "Sochi":
        break
    count += 1

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

break语句表示您将退出while循环。

答案 3 :(得分:1)

为什么不尝试更多的pythonic解决方案?

places = ["Jack", "John", "Sochi"]

try:
    count = places.index("Sochi")
except ValueError:
    count = len(places)

multi_word = len([place for place in places[:count] if ' ' in place])