如何使用while循环确定列表中大于平均值的数量

时间:2019-03-14 18:09:43

标签: python

嗨,我需要以两种方式执行此任务:一种是使用for循环进行的方式,另一种是使用while循环进行的方式,但是我没有割礼。...我编写的代码是:

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

4 个答案:

答案 0 :(得分:1)

您的代码确实未格式化。通常:

for x in some_list:
    ... # Do stuff

等效于:

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

答案 1 :(得分:1)

问题是您在代码中使用while float in A > AV:。在条件成立之前,while将起作用。因此,一旦列表中遇到一些小于平均数的数字,循环就会退出。因此,您的代码应为:

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
i = 0
while i < len(A):
  if A[i] > AV: count += 1
  i += 1
print ("The number of elements bigger than the average is: " + str(count))

我希望它能对您有所帮助:),我相信您知道为什么我添加了另一个变量i

答案 2 :(得分:0)

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
i = 0
while i < len(A):
    if A[i] > AV:
        count += 1
    i += 1

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

答案 3 :(得分:0)

您可以使用类似下面的代码。我对每个部分都进行了评论,解释了重要的部分。请注意,您的while float in A > AV在python中无效。对于您自己的情况,应该通过索引或使用带有for关键字的in循环来访问列表的元素。

# In python, it is common to use lowercase variable names 
# unless you are using global variables
a = [5, 8, 4, 1, 2, 9]
avg = sum(a)/len(a)
print(avg)

gt_avg = sum([1 for i in a if i > avg])
print(gt_avg)

# Start at index 0 and set initial number of elements > average to 0
idx = 0
count = 0
# Go through each element in the list and if
# the value is greater than the average, add 1 to the count
while idx < len(a):
    if a[idx] > avg:
        count += 1
    idx += 1
print(count)

上面的代码将输出以下内容:

  

4.833333333333333
  3
  3

注意:我提供的列表理解有多种选择。您也可以使用这段代码。

gt_avg = 0
for val in a:
    if val > avg:
        gt_avg += 1