Using while loops to count elements in a list

拜拜、爱过 提交于 2019-11-30 09:56:56

问题


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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/19359093/using-while-loops-to-count-elements-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!