到达列表的某个元素时停止while循环

时间:2013-10-09 18:06:46

标签: python loops while-loop

places= ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center",  "LA Dodgers stadium", "Home"]
def placesCount(places):
    multi_word = 0
    count = 0
    while True:
        place = places[count]
        if ' ' in place and place!='LA Dodgers stadium' **""" or anything that comes after LA dogers stadium"""** :
            multi_word += 1
        if '' in place and place!='LA Dodgers stadium' """ **or anything that comes after LA dogers stadium**""":
            count += 1
    print (count, "places to LA dodgers stadium"),  print (multi_word)
placesCount(places)

在这种情况下,当我到达列表的某个元素("LA Dodgers Stadium")时,我基本上想知道如何阻止while循环添加到列表中。它到达列表中的元素后不应添加任何内容。

3 个答案:

答案 0 :(得分:3)

您的代码似乎有效。这是一个稍好的版本:

def placesCount(places):
    count = 0
    multi_word = 0
    for place in places:
        count += 1
        if ' ' in place:
            multi_word += 1
        if place == 'LA Dodgers stadium':
            break
    return count, multi_word

或使用itertools

from itertools import takewhile, ifilter

def placesCount(places):
    # Get list of places up to 'LA Dodgers stadium'
    places = list(takewhile(lambda x: x != 'LA Dodgers stadium', places))

    # And from those get a list of only those that include a space
    multi_places = list(ifilter(lambda x: ' ' in x, places))

    # Return their length
    return len(places), len(multi_places)

然后你可以使用这个函数的一个例子(没有改变你的原始示例BTW,函数仍然表现相同 - 接受一个位置列表并返回一个带有两个计数的元组):

places = ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center",  "LA Dodgers stadium", "Home"]

# Run the function and save the results
count_all, count_with_spaces = placesCount(places)

# Print out the results
print "There are %d places" % count_all
print "There are %d places with spaces" % count_with_spaces

答案 1 :(得分:1)

这段代码似乎运行得很好。我打印出placesCount的结果,这是(6,5)。看起来这意味着该功能点击了6个单词,其中5个是多个单词。这符合您的数据。

正如弗雷德里克所提到的,在地方循环中使用一个地方将是一个更好的方式来完成你想要做的事情。

答案 2 :(得分:0)

place = None
while place != 'stop condition':
    do_stuff()