Python 当到达列表的某个元素时停止while循环
我基本上想知道,在这种情况下,当while循环到达列表的某个元素(Python 当到达列表的某个元素时停止while循环,python,loops,while-loop,Python,Loops,While Loop,我基本上想知道,在这种情况下,当while循环到达列表的某个元素(“LA Dodgers Stadium”)时,如何阻止它添加到列表中。在到达列表的该元素后,不应添加任何内容。此代码似乎工作正常。我打印了PlaceScont的结果,结果是(6,5)。看起来这意味着函数命中了6个单词,其中5个是多单词。这符合你的数据 places= ["Home","In-n Out Burger", "John's house", "Santa Monica Pier", "Staples center",
“LA Dodgers Stadium”
)时,如何阻止它添加到列表中。在到达列表的该元素后,不应添加任何内容。此代码似乎工作正常。我打印了PlaceScont的结果,结果是(6,5)。看起来这意味着函数命中了6个单词,其中5个是多单词。这符合你的数据
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)
正如Fredrik提到的,使用for-place-in-places循环可以更好地完成您想要做的事情 您的代码似乎正常工作。下面是一个稍微好一点的版本:
place = None
while place != 'stop condition':
do_stuff()
或使用:
下面是一个如何使用该函数的示例(与原始示例相同,顺便说一句,该函数的行为仍然相同-接受一个位置列表并返回一个包含两个计数的元组):
这不管用吗?用
代替while thingie,用代替placein places:
在你们的位置上循环;那么您就不需要对空白进行任何特殊处理。还有,为什么不做一个简单的len(places)
?这可能是OP想要的,+1我如何打印结果?打印(PlaceScont)无效如何打印结果?print(PlaceScont)不起作用如果您的函数返回任何类型的数据(如数字、列表等),您应该可以执行print PlaceScont(PlaceScont)。
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
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