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)

次に関数を使用する方法の例(元の例から変更されていませんが、関数は同じように動作します-場所のリストを受け入れ、2つのカウントを持つタプルを返します):

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

このコードは問題なく動作するようです。placeCount の結果 (6, 5) を出力しました。これは、関数が 6 つの単語にヒットし、そのうち 5 つが複数の単語であったことを意味するようです。それはあなたのデータに適合します。

Fredrik が述べたように、for place in places ループを使用すると、目的を達成するためのより適切な方法になります。

于 2013-10-09T18:24:47.617 に答える