list []
list contains [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
如何從列表中獲得每10個數字的平均值?如何獲得Python中列表中每10個數字的平均值
list []
list contains [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
如何從列表中獲得每10個數字的平均值?如何獲得Python中列表中每10個數字的平均值
下面是示例代碼。遍歷您的案例中每個step
即10
的數字列表。計算步驟之間元素的average
。
>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
>>> step = 10
>>> for i, _ in enumerate(my_list[::step]):
... sub_list = my_list[i*10:] if (i+1)*10 > len(my_list) else my_list[i*10:(i+1)*10] # Condition if the len(my_list) % step != 0
... print sum(sub_list)/float(len(sub_list)) # Dividing by float' to get decimal value as average (Not needed in Python 3)
...
5.5
15.5
25.5
的平均值可被計算,而不創建子列表:
testdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
LEN = 10
def avg(data):
datasum = cnt = 0
for num in data:
datasum += num
cnt += 1
if cnt == LEN:
yield datasum/LEN
datasum = cnt = 0
if cnt:
yield datasum/cnt
print(list(avg(testdata)))
# [5.5, 15.5, 25.5]
另一個實現與子列表:
def avg(data):
for i in range((len(data) + LEN - 1) // LEN):
sublist = data[i*LEN:(i+1)*LEN]
yield sum(sublist)/len(sublist)
注意:這是Python3代碼其中int/int是浮動。在Python2中int/int是int。
解釋你的代碼應該做什麼。什麼是投入和預期產出。現在你的代碼中發生了什麼,導致你認爲它不起作用。最終,請閱讀如何整合更好的[mcve]並相應地編輯您的問題。 – idjaw
按「每10個數字的平均數」,你的意思是「平均數爲1-10」,然後是「11-20」等等? –
每10個數字組合就會產生3千萬次平均值! – VPfB