我正在尝试找到一种有效的方法来执行以下操作:
我有这个样本:
sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]
并且需要
res = [['no', 6, 15], ['ja', 15, 18], ['ap',7,12]]
即。求和第一个元素相同的子列表的相应值。
非常感谢
我的代码是:
codes = list(set([element[0] for element in sample]))
res=[]
for code in codes:
aux=[code]
res01 = 0
res02 = 0
for element in sample:
if element[0] == code:
res01 += element[1]
res02 += element[2]
aux += [res01, res02]
res.append(aux)
答案 0 :(得分:3)
使用defaultdict
:
>>> from collections import defaultdict
>>> d = defaultdict(lambda: [0,0], list())
>>> for a,b,c in sample:
d[a][0]+=b
d[a][1]+=c
#driver values:
IN : sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]]
OUT : d = defaultdict(<function <lambda> at 0x7f4349f17620>,
{'no': [6, 15], 'ja': [15, 18], 'ap': [7, 12]})
由于输出是这样构造的,我建议您使用dict
类型来存储输出,因为将来处理它会更容易。
如果您仍希望输出为list
,只需映射dict
,如下所示:
>>> [ [key]+ele for key,ele in d.items()]
=> [['no', 6, 15], ['ja', 15, 18], ['ap', 7, 12]]
答案 1 :(得分:0)
import pandas as pd
x=pd.DataFrame(sample).groupby(0).agg({1:"sum", 2:"sum"})
d=x.to_dict(orient="split")
#{'columns': [1, 2], 'data': [[7, 12, 'ap'], [15, 18, 'ja'], [6, 15, 'no']],'index': ['ap', 'ja', 'no']}
[d["data"][i]+[d["index"][i]] for i in range(0, len(d["data"]))]
-----OUTPUT-----------
[[7, 12, 'ap'], [15, 18, 'ja'], [6, 15, 'no']]