[英]How to use a while loop to count the number of times a specific number appears in a list?
我有一个来自作业的问题:
编写一个程序,接收一系列数字(以 0 结尾)并计算数字 100 在列表中出现的次数。 例如,对于系列 2, 6, 100, 50, 101, 100, 88, 0,它会输出 2。
我已经能够使用 for 循环成功地做到这一点,但我应该用一个 while 循环来执行它。
我的 for 循环是:
list = [2, 6, 100, 50, 101, 100, 88, 0]
n=list[0]
total=0
if n !=0:
for n in list:
if n == 100:
total +=1
print (total)
但是我似乎无法通过 while 循环获得 2 的输出。 我尝试了一些变体,输出为 0,其中之一是:
list = [2, 6, 100, 50, 101, 100, 88, 0]
n=list[0]
total=0
if n !=0:
while n in list == 100:
total +=1
print (total)
有人可以建议使用 while 循环实现相同输出的最简单方法吗? 谢谢!
您可以将索引设置为 0 并使用 while 循环继续查找,直到索引与列表的长度相同。 在每次迭代中检查列表的该索引的值是否等于 100 并且它是否确实将总数增加了 1
nums = [2, 6, 100, 50, 101, 100, 88, 0]
index = 0
total = 0
while index < len(nums):
if nums[index] == 100:
total += 1
index +=1
print(total)
解决这个问题的最快方法是保持迭代/索引值并在 while 循环中递增。 你似乎在想
对于列表语法中的项目。
尝试这个。
list = [2, 6, 100, 50, 101, 100, 88, 0]
iter = 0
n=list[iter]
total=0
while n != 0:
if(n == 100):
total += 1
iter += 1
n = list[iter]
print (total)
这假设您将始终以 0 结束列表。
虽然这可以通过替换 while 循环变得更容易,但我假设它是您的要求:
list = eval(input('Enter List: '))
n, total, a = True, 0, 0
length = len(list)
while n is True:
if a == length:
n = False
elif list[a] == 100:
total += 1
a += 1
print(total)
您可以坚持使用 while True 并使用enumerate方法来循环遍历列表的索引和列表的元素,如下所示:
your_list = [2, 6, 100, 50, 101, 100, 88, 0]
counter = 0
index = 0
while True:
for index,element in enumerate(your_list):
if 100 == element:
counter += 1
#break while:
if index == len(your_list) - 1:
print(counter)
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.