0
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"中。在到达列表的该元素后,它不应添加任何内容。

4

3 回答 3

2

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

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
于 2013-10-09T18:25:43.170 回答
0
place = None
while place != 'stop condition':
    do_stuff()
于 2013-10-09T18:15:23.663 回答
0

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

正如 Fredrik 所提到的,使用 for place in places 循环将是完成您想要做的事情的一种更漂亮的方式。

于 2013-10-09T18:24:47.617 回答