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

2024-04-25 22:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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


Tags: andinhome列表ifcountplacemulti
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)

下面是一个如何使用函数的示例(与原来的示例没有变化,顺便说一句,函数的行为仍然相同-接受一个位置列表并返回一个包含两个计数的元组):

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

这个代码似乎工作得很好。我打印了placeScont的结果,结果是(6,5)。看起来这意味着函数命中了6个单词,其中5个是多单词。符合你的数据。你知道吗

正如Fredrik提到的,使用for place-in-places循环将是一种更好的方法来完成您要做的事情。你知道吗

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

相关问题 更多 >