簡體   English   中英

計算列表中50或更大的所有數字的平均值?

[英]Compute the average of all numbers in a list that are 50 or greater?

我想返回一個函數,它給出所有50或更多標記的平均值。 當我運行我的代碼時,它總是返回一個空列表。 這是我嘗試過的:

def get_pass_average(marks):
    average = []
    for count in marks:
        if count >= 50:
           average = sum(count) / len(count)          
    return round(average,2)

def test_get_pass_average():
    list1 = [50, 83, 26, 65, 92, 29, 77, 64]
    print('%.2f' % (get_pass_average(list1)))

請幫我弄清楚代碼中的問題,輸出應該是71.83。

嘗試這個:

l=[i for i in list1 if i>=50]
print(sum(l)/len(l))

要么:

from statistics import mean
l=[i for i in list1 if i>=50]
print(mean(l))

如果想要條件為空列表:

l=[i for i in list1 if i>=50]
if l:
    print(sum(l)/len(l))

要么:

from statistics import mean
l=[i for i in list1 if i>=50]
if l:
    print(mean(l))

對於python 2:

print(sum(l)/len(l))

應該:

print(float(sum(l))/float(len(l)))

而且沒有統計模塊。

您的代碼不起作用,因為您將迭代器(整數)求和而不是列表,這就是為什么它不能正常工作

除了U9-Forward的答案之外,還有一個使用filtermean

from statistics import mean

list1 = [50, 83, 26, 65, 92, 29, 77, 64]
average = mean(filter((50).__le__, list1))
print('%.2f' % average)

回答以下問題:

請幫我弄清楚代碼中的問題

問題是:

for count in marks
    if count >= 50:
        average = sum( count ) / len( count )

marks是整數列表。 因此,當你圈for count in marks ,價值count是整數。 我在Python 3.6.3和2.7.10中測試了你的代碼,你甚至不能在整數上調用sum()len()函數(如果你嘗試的話它們都會返回一個TypeError )。

你初始化average = [] ,所以看起來你希望average包含一個列表,但即使sum( count ) = countlen( count ) = 1 ,那么average包含一個整數,而不是一個列表。

我很想知道你正在使用哪個版本的Python,它允許這些代碼無誤地執行。

已經給出了對這些錯誤的更正。

實際上,你提供的代碼並沒有返回一個空列表,因為你聲明它實際上是以一個TypeError聲明,假設你實際上調用test_get_pass_average()函數,這在你的代碼中是不明確的:

Traceback (most recent call last):
  File "testprog.py", line 12, in <module>
    test_get_pass_average()
  File "testprog.py", line 10, in test_get_pass_average
    print('%.2f' % (get_pass_average(list1)))
  File "testprog.py", line 5, in get_pass_average
    average = sum(count) / len(count)          
TypeError: 'int' object is not iterable

可能是你假設它打印一個空列表,因為沒有輸出但是,除非你調用測試函數,否則不會任何輸出,只是因為你提供的代碼定義了兩個函數但沒有做任何其他事情。

你的代碼斷言的原因 (當你稱呼它)很簡單,因為你傳遞一個非迭代int變量sum() sum()函數需要一個iterable,因為它迭代每個項目來計算總和 - 你不能迭代一個整數(即使你可以, len()也會失敗,因為int類型沒有這樣的函數:

TypeError: object of type 'int' has no len()

您嘗試對int執行此操作的原因是因為構造:

for variable in [3,1,4,1,5,9]:

將迭代該列表,依次為每個元素設置variable 所以variable將是一個int ,無法受到sum()len()


在修復它時,以下函數為您提供了所需數據的一般解決方案,所有數字的平均值大於或等於某個閾值,並且如果沒有數字可用,則允許特定結果(默認為None ):

def AverageWithThreshold(myList, threshold, emptyResult = None):
    newList = [item for item in myList if item >= threshold]
    if len(newList) == 0: return emptyResult
    return sum(newList) / len(newList)

對於您的具體情況,您可以使用類似的方式調用它(我們假設空列表的平均值應為零):

print('%.2f' % (AverageWithThreshold(list1, 50, 0)))

幾乎所有其他內容都被覆蓋, filter在這里也有用處

l = list(filter(lambda x: x >= 50, marks))
print('%.2f' % (sum(l)/len(l)))
 71.83 

要解釋代碼有什么問題:

  • 您將平均值的迭代器(整數)相加。

  • 而且你得到它的長度,你不能,因為它是一個整數。

存儲值並稍后計算平均值,而不是嘗試計算for循環內部的平均值。

希望你是在找這個:

def get_pass_average(marks):
    marksAbove = []
    for count in marks:
        if count >= 50:
            marksAbove.append(count);

    average = sum(marksAbove) / len(marksAbove)  
    return round(average,2)

def test_get_pass_average():
    list1 = [50, 83, 26, 65, 92, 29, 77, 64]
    print('%.2f' % (get_pass_average(list1)))

# Init
test_get_pass_average()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM