Python 如何使用while循环计算特定数字在列表中出现的次数?

Python 如何使用while循环计算特定数字在列表中出现的次数?,python,Python,我有一个作业中的问题: 编写一个程序,接受一系列以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: tot

我有一个作业中的问题:

编写一个程序,接受一系列以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,以及它是否将total增加1

nums=[2,6100,50101100,88,0] 索引=0 总数=0 当指数处理这个问题的最快方法是在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方法来循环列表索引和列表元素,如下所示:

你的清单=[2,6100,50101100,88,0] 计数器=0 索引=0 尽管如此: 对于索引,枚举列表中的元素: 如果100==元素: 计数器+=1 中途休息: 如果index==lenyour_列表-1: 打印计数器 打破
你可以使用一个计数器变量来增加每个循环并限制while as i