矩阵如下:1,2017,2,51,2018,1,51,2018,2,42,2017,1,51,2018,1,2根据前三列分出三种,产生新的矩阵:1,2017,2,51,2018,1,71,2018,2,42,2017,1,5少了一行,是因为只要前三列相同,那第四列求和,2+5=7如何计算?
1 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
就是分组求和的思想。
m = [[1,2017,2,5],[1,2018,1,5],[1,2018,2,4],[2,2017,1,5],[1,2018,1,2]]# 先建立个dict,# 前三项作为key, 第四项作为valued = dict()for i in m: d_key = tuple(i[:-1]) d_value = i[-1] if d_key not in d: d.update({d_key:d_value}) else: d[d_key] += d_value # 再把dict转为数组result = list()for d_key,d_value in d.items(): tmp = list(d_key) tmp.append(d_value) result.append(tmp) print(result)
result就是:
[[1, 2018, 2, 4], [1, 2018, 1, 7], [2, 2017, 1, 5], [1, 2017, 2, 5]]
- 1 回答
- 0 关注
- 314 浏览
添加回答
举报
0/150
提交
取消