首页 > 解决方案 > 如何使用while循环来确定列表中大于平均值的数字数量

问题描述

嗨,我需要以两种方式完成这项任务:一种方式使用 for 循环,另一种方式使用 while 循环,但我没有 secceed....我写的代码是:

A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0

for i in A : 
    if i > AV : 
        count = count + 1

print ("The number of elements bigger than the average is: " + str(count))
count = 0
while float in A > AV:
    count += 1

print ("The number of elements bigger than the average is: " + str(count))

标签: python

解决方案


您的代码确实未格式化。一般来说:

for x in some_list:
    ... # Do stuff

相当于:

i = 0
while i < len(some_list):
   ... # Do stuff with some_list[i]
   i += 1

推荐阅读