0

嗨,我需要以两种方式完成这项任务:一种方式使用 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))
4

4 回答 4

1

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

for x in some_list:
    ... # Do stuff

相当于:

i = 0
while i < len(some_list):
   ... # Do stuff with some_list[i]
   i += 1
于 2019-03-14T18:15:29.807 回答
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

于 2019-03-14T18:26:38.730 回答
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))
于 2019-03-14T18:14:55.047 回答
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
于 2019-03-14T18:35:12.823 回答