簡體   English   中英

如何獲取列表中索引值的總和和平均值?

[英]How to take sum and average of indexed values in a list?

使用groupby在列表A具有相鄰匹配值的索引位置擴展列表B

A = [476, 1440, 3060, 3060, 500,500]
B = [0,4,10,15]

因此,結果列表為:

B_update1 = [0,4,10,10,15,15]

經過一些中間步驟后將是:

B_update2 = [0,4,12,10,20,20]

現在我想取重復值的總和和均值,這將給我以下信息:

B_mean = [0,4,11,20]
B_sum = [0,4,22,40]

我不確定該怎么做。 有什么建議么?

B_update1, B_update2, B_mean, B_sum = [0,4,10,10,15,15], [0,4,12,10,20,20], [],[]
from itertools import groupby
from operator import itemgetter
for num, grp in groupby(enumerate(B_update1), itemgetter(1)):
    tmp_list = [B_update2[idx] for idx, _ in grp]
    B_mean.append(sum(tmp_list)/len(tmp_list))
    B_sum.append(sum(tmp_list))
print B_mean, B_sum

產量

[0, 4, 11, 20] [0, 4, 22, 40]

您本質上需要的信息是重復次數:

>>> A = [476, 1440, 3060, 3060, 500, 500]
>>> B = [0, 4, 10, 15]
>>> repetitions = [len(list(g)) for n, g in groupby(A)]
>>> repetitions
[1, 1, 2, 2]

由此,您可以構造B_update1並返回到簡單列表:

>>> B_update1 = []
>>> for i, r in enumerate(repetitions):
        B_update1.extend([B[i]] * r)
>>> B_update1
[0, 4, 10, 10, 15, 15]

>>> B_update2 = [0, 4, 12, 10, 20, 20] # MAGIC

>>> B_sum, B_mean = [], []
>>> i = 0
>>> for r in repetitions:
        s = sum(B_update2[i:i + r])
        B_sum.append(s)
        B_mean.append(s / r)
        i += r

>>> B_sum
[0, 4, 22, 40]
>>> B_mean
[0.0, 4.0, 11.0, 20.0]

暫無
暫無

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

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