使用 while 循环计算列表中的元素 [英] Using while loops to count elements in a list
本文介绍了使用 while 循环计算列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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)
我的代码应该打印 Sochi 之前的城市数量,不包括 Sochi .我不明白这行 (place =places[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 将其整理好
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
这篇关于使用 while 循环计算列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文