【问题标题】:Stopping a while loop when a certain element of the list is reached到达列表的某个元素时停止 while 循环
【发布时间】:2013-10-10 04:09:31
【问题描述】:
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") 时,如何阻止它添加到列表中。在到达列表的那个元素之后,它不应该添加任何东西。

【问题讨论】:

  • 这不行吗?
  • 使用for place in places: 来循环你的位置而不是while-thingie;那么您不需要对空格进行任何特殊处理。还有为什么不简单的len(places)

标签: python loops while-loop


【解决方案1】:

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

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

【讨论】:

  • 这可能是OP所追求的,+1
  • 如何打印结果?打印(placesCount)不起作用
【解决方案2】:
place = None
while place != 'stop condition':
    do_stuff()

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 如何打印结果?打印(placesCount)不起作用
    • 如果您的函数返回任何类型的数据(如数字、列表等),您应该能够打印 placesCount(places)。
    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多