-5
places=["Jack", "John", "Sochi"]
place = places[0]
while places != "Sochi" and count < len(places):

    if ' ' in place:
        multi_word += 1

    count += 1
    place = places[count]

我基本上希望程序通过为列表的每个元素添加一个来检查索契之前有多少个城市。然后,当它到达索契时,它会停止向列表中添加 1,然后当它到达索契时它什么也不做。该程序为列表的每个元素添加一个。然后它检查它们是否是列表的任何元素中的空格,如果是,则添加一个,但前提是列表的该元素来自索契。这个程序有什么问题?这行还有什么作用..{count < len(places)}

4

2 回答 2

1

我看到的主要错误是您需要检查if place != "Sochi",而不是使用places. 假设您初始化count=0,这将为您提供所需的输出:

places = ["Jack", "John", "Sochi"]
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

该子句count < len(places)确保您不会尝试访问places超出列表长度的索引,这将返回一个IndexError.

于 2013-10-10T02:42:46.647 回答
-3
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)

这是固定代码

于 2013-10-10T02:51:06.450 回答