简体   繁体   中英

Using while loops to count elements in a list

places = ["Jack", "John", "Sochi"]
count=0
multi_word=0
place  = places[count]
while place != "Sochi" and count < len(places):
    if ' ' in place:
        multi_word += 1

    count += 1
    place = places[count]

print ('Number of cities before Sochi:', count)

My code should print the number of cities before Sochi excluding Sochi . I don't understand what this line (place = places[count]) does, nor do I understand why I need it twice.

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
count=0
place = places[count]

Now place is always places[0] , ie 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.

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM