繁体   English   中英

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

[英]how to use while loop to determine the amount of numbers in a list that are greater the average

嗨,我需要以两种方式执行此任务:一种是使用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))

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

for x in some_list:
    ... # Do stuff

等效于:

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

问题是您在代码while float in A > AV:中使用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

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

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

# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM