4 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
假設(shè)您想按數(shù)字的整數(shù)值進(jìn)行分組(因此數(shù)字向下舍入),這樣的方法可以工作:
>>> a = [0, 0.5, 1, 1.5, 2, 2.5]
>>> groups = [list(g) for _, g in itertools.groupby(a, int)]
>>> groups
[[0, 0.5], [1, 1.5], [2, 2.5]]
那么求平均就變成:
>>> [sum(grp) / len(grp) for grp in groups]
[0.25, 1.25, 2.25]
這假設(shè)a已經(jīng)排序,如您的示例所示。

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您使用其他庫(kù)沒(méi)有問(wèn)題:
import pandas as pd
import numpy as np
a = [0, 0.5, 1, 1.5, 2, 2.5]
print(pd.Series(a).groupby(np.array(a, dtype=np.int32)).mean())
給出:
0 0.25
1 1.25
2 2.25
dtype: float64

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您想要使用字典的方法,您可以像這樣繼續(xù):
dic={}
a = [0, 0.5, 1, 1.5, 2, 2.5]
for items in a:
if int(items) not in dic:
dic[int(items)]=[]
dic[int(items)].append(items)
print(dic)
for items in dic:
dic[items]=sum(dic[items])/len(dic[items])
print(dic)

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用groupby
輕松獲得它(您可能需要先對(duì)列表進(jìn)行排序):
from itertools import groupby
from statistics import mean
a = [0, 0.5, 1, 1.5, 2, 2.5]
for k, group in groupby(a, key=int):
? ? print(mean(group))
會(huì)給:
0.25
1.25
2.25
添加回答
舉報(bào)