python 值相同,列分别相加?

待处理数据如下:
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)
阅读 5.7k
2 个回答

这个最好还是用Pandas等库去实现,根据你的需求我重新造个轮子:

from collections import defaultdict

course_to_score = defaultdict(lambda: [0, 0, 0])
def add(line):
    row = line.rstrip().split()
    course_to_score[int(row[-1])] = map(sum, zip(course_to_score[int(row[-1])], map(float, row[: -1])))    
with open('1.txt') as handle:
    [add(line) for line in handle]   
sorted(course_to_score.iteritems(), key=lambda item: item[0])
from collections import defaultdict

with open('1.txt', 'r') as f:
    # 读取文件的数据
    data = [[float(item) for item in line.split()] for line in f]
    # 合并最后一列相同的行
    tmp_data = defaultdict(list)
    [tmp_data[d[-1]].append(d) for d in data]
    # 把最后一列相同的行的前面的列相加
    new_data = [map(sum, zip(*lists)[0:-1]) + [lists[0][-1]] for lists in tmp_data.values()]
    # 对新数据进行排序
    new_data.sort(key=lambda x: x[-1])
    print new_data
    
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题