待处理数据如下:
0.2 0.3 0.5 1
0.3 0.1 0.2 3
0.4 0.2 0.3 1
0.2 0.2 0.2 2
0.3 0.3 0.3 2
0.3 0.2 0.6 3
0.1 0.1 0.1 4
如果最后一列相同(全是整数),则前面的列分别相加,然后按照最后一列排序(从小到大)
结果:
0.6 0.5 0.8 1
0.5 0.5 0.5 2
0.6 0.3 0.8 3
0.1 0.1 0.1 4
我的代码(不含排序),这种解决方法不是很好,代码思路是先合并行,在打印(通过列举的办法)是否还有更好的办法?
with open('1.txt', 'r') as f:
alist = []
d = {}
lines = f.readlines()
for line in lines:
line = line.strip().split()
alist.append(line)
for i in alist:
try:
d[i[3]] += i[:-1]
except KeyError:
d[i[3]] = i[:-1]
for course, score in d.items():
if len(score) > 3:
print course, float(score[0]) + float(score[3]), float(score[1]) + float(score[4]), \
float(score[2]) + float(score[5])
else:
print course, ' '.join(score)
这个最好还是用Pandas等库去实现,根据你的需求我重新造个轮子: