Using while loops to count elements in a list

前端 未结 4 597
陌清茗
陌清茗 2020-12-22 07:23
places = [\"Jack\", \"John\", \"Sochi\"]
count=0
multi_word=0
place  = places[count]
while place != \"Sochi\" and count < len(places):
    if \' \' in place:
             


        
相关标签:
4条回答
  • 2020-12-22 07:34

    You can use the following while loop to check for the number of places before Sochi:

    places = ["Jack", "John", "Sochi"]
    count = 0
    multi_word = 0
    while count < len(places):
        place = places[count]
        if ' ' in place:
            multi_word += 1
        if place == "Sochi":
            break
        count += 1
    
    print('Number of cities before Sochi:', count)
    

    The break statement means you'll exit your while loop.

    0 讨论(0)
  • 2020-12-22 07:38

    foreach would neaten it up

    places = ["Jack", "John", "Sochi"]
    count = 0
    for place in places:
        if ' ' in place:
            multi_word += 1
        if place == "Sochi":
            break
        count += 1
    
    0 讨论(0)
  • 2020-12-22 07:40
    count=0
    place = places[count]
    

    Now place is always places[0], i.e. Jack. Thus the while loop only terminates on the second condition, giving you the list length of 3.

    place = places[count] should go in the loop.

    0 讨论(0)
  • 2020-12-22 07:52

    Why not try a more pythonic solution instead ?

    places = ["Jack", "John", "Sochi"]
    
    try:
        count = places.index("Sochi")
    except ValueError:
        count = len(places)
    
    multi_word = len([place for place in places[:count] if ' ' in place])
    
    0 讨论(0)
提交回复
热议问题