[英]Stopping a while loop when a certain element of the list is reached
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)
I basically want to know how I can stop the while-loop from adding to the list when it reaches a certain element of the list ( "LA Dodgers Stadium"
) in this case. 我基本上想知道在这种情况下,当while循环到达列表的某个元素(
"LA Dodgers Stadium"
)时,如何停止将while循环添加到列表中。 It should not add anything after it reaches that element of the list. 到达列表的该元素后,不应添加任何内容。
Your code seem to work. 您的代码似乎可以正常工作。 Here is a slightly better version:
这是一个更好的版本:
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
Or using itertools : 或使用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)
An example of how you could then use the function (that didn't change from your original example BTW, the function still behaves the same - accepts a list of places and returns a tuple with the two counts): 然后说明如何使用该函数的示例(与原始示例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
This code seems to work just fine. 该代码似乎可以正常工作。 I printed out the result of placesCount, which was (6, 5).
我打印出placesCount的结果,它是(6,5)。 Looks like this means the function hit 6 words, of which 5 were multi words.
看起来这意味着该函数命中了6个单词,其中5个是多单词。 That fits with your data.
这符合您的数据。
As Fredrik mentioned, using a for place in places loop would be a prettier way of accomplishing what you're trying to do. 正如Fredrik提到的,使用for place in place循环将是完成您要尝试的操作的更漂亮的方法。
place = None
while place != 'stop condition':
do_stuff()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.