Python合并列表以逗号分隔的方式将唯一值汇总

时间:2016-09-13 13:08:35

标签: python

我正试图让它发挥作用。

这是我的数据:

data.csv

id,fname,lname,education,gradyear,attributes
1,john,smith,mit,2003,qa
1,john,smith,harvard,207,admin
1,john,smith,ft,212,master
2,john,doe,htw,2000,dev

尝试使用此代码。在互联网上找到此代码,并不完全了解它。

from itertools import groupby
import csv
import pprint


t = csv.reader(open('data.csv'))
t = list(t)


def join_rows(rows):
    def join_tuple(tup):
        for x in tup:
            if x: 
                return x
        else:
            return x
    return [join_tuple(x) for x in zip(*rows)]



for name, rows in groupby(sorted(t), lambda x:x[0]):
    print join_rows(rows)

但是,它不会将逗号分隔的唯一值合并。

输出结果为:

['1', 'john', 'smith', 'ft', '212', 'master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']

我怎样才能做到:

['1', 'john', 'smith', 'mit,harvard,ft', '2003,207,212', 'qa,admin,master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']

如果同一列的条目更多,它也应该有效。不应限于3行。

Grrrrr ....任何人都有提示或想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

您可以将join_rows的定义更改为

import itertools

def join_rows(rows):
    return [(e[0] if i < 3 else ','.join(e)) for (i, e) in enumerate(zip(*rows))]

这样做是将属于同一个id的所有条目压缩为元组。对于前3个元组,返回第一个项目;对于后者,他们加上了逗号。

['1', 'john', 'smith', 'ft,harvard,mit', '212,207,2003', 'master,admin,qa']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']