![](/img/trans.png)
[英]Take the average and go through the list again. Count the amount of numbers greater than the average and the amount of numbers less than the average
[英]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.