2

我有一个 CSV 文件,它是这样的:

['Name1','','','','','','','','','','','','','','','', '', '', '', '', '+']
['Name1', '', '', '', '', '', 'b', '', '', '', ' ', '', '', '', '', '', '', '', '', '', '']
['Name2', '', '', '', '', ' ','','','','','','','','','','','','','','a','']
['名称3', '', '','','','+','','','','','','','','','','','','','' , '', '']

现在,我需要一种方法将具有相同第一列名称的所有行加入一列,例如:

['Name1','','','','','','b','','','','','','','','','' , '', '', '', '', '+']
['Name2', '', '', '', '', '', '', '', '', '', ' ', '', '', '', '', '', '', '', '', 'a', '']
['Name3', '', '', '', '', '+', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

我可以通过对 CSV 进行排序然后遍历每一行和每一列并比较每个值来想办法做到这一点,但可能应该有一种更简单的方法来做到这一点。

有任何想法吗?

4

3 回答 3

3

您应该使用 itertools.groupby:

t = [ 
['Name1', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '+'],
['Name1', '', '', '', '', '', 'b', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['Name2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'a', ''],
['Name3', '', '', '', '', '+', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] 
]

from itertools import groupby

# TODO: if you need to speed things up you can use operator.itemgetter
# for both sorting and grouping
for name, rows in groupby(sorted(t), lambda x:x[0]):
    print join_rows(rows)

很明显,您将在单独的函数中实现合并。例如像这样:

def join_rows(rows):
    def join_tuple(tup):
        for x in tup:
            if x: 
                return x
        else:
            return ''
    return [join_tuple(x) for x in zip(*rows)]
于 2012-06-14T11:43:33.033 回答
1
def merge_rows(row1, row2):
    # merge two rows with the same name
    merged_row = ...
    return merged_row

r1 = ['Name1', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '+']
r2 = ['Name1', '', '', '', '', '', 'b', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
r3 = ['Name2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'a', '']
r4 = ['Name3', '', '', '', '', '+', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
rows = [r1, r2, r3, r4]
data = {}
for row in rows:
    name = row[0]
    if name in data:
        data[name] = merge_rows(row, data[name])
    else:
        data[name] = row

您现在拥有所有行,data其中该字典的每个键是名称,对应的值是该行。您现在可以将此数据写入 CSV 文件。

于 2012-06-14T11:25:57.330 回答
0

您还可以使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> _ = [d[i[0]].append(z) for i in t for z in i[1:]]
>>> d['Name1']
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '+', '', '', '', '', '', 'b', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

然后加入你的专栏

于 2012-06-14T12:38:43.817 回答