rescot
rescot

Reputation: 335

python merge rows on cell in 2-dimensional list

I would like to merge cells in 2d list, new rows are merged on next empty row. struggling with the logic to design this. I parsed an html table and turn it into 2 dimensional list and would like to merge rows that separated by empty rows. eg.

data = [[a, b, c]
[d, e, f]
['','','']
[q, r, s]
[t, u, v]
[m, n, o]
['','','']
[g, h, i]
[j, k, l]]

results should be:

new_data = [[ad, be,cf]
[qtm, run, svo]
[gj, hk, il]]

This is my function and am stucked progressing it.

def _merge_data_cells(table_grid):
    header, data = table_grid
    if header is None or data is None:
        return
    offset_row = True
    while offset_row:
        for i, row in enumerate(data):
            if is_empty(row):
                offset_row = False
                break
            for cell in row:

    return header, data

Thank in advance for the help.

Upvotes: 0

Views: 224

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95957

Assuming you are working with strings, use itertools.groupby and any:

In [6]: data = [['a', 'b', 'c'],
   ...: ['d', 'e', 'f'],
   ...: ['','',''],
   ...: ['q', 'r', 's'],
   ...: ['t', 'u', 'v'],
   ...: ['m', 'n', 'o'],
   ...: ['','',''],
   ...: ['g', 'h', 'i'],
   ...: ['j', 'k', 'l']]

In [7]: from itertools import groupby

In [8]: grouped = groupby(data, any)

In [9]: [list(map(''.join, zip(*g))) for k, g in grouped if k]
Out[9]: [['ad', 'be', 'cf'], ['qtm', 'run', 'svo'], ['gj', 'hk', 'il']]

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

Your may create a list comprehension using zip and itertools.groupby to achieve this as:

>>> from itertools import groupby

>>> [[''.join(x) for x in zip(*j)] for i, j in groupby(data, lambda x: x[0]!='') if i]
[['ad', 'be', 'cf'], ['qtm', 'run', 'svo'], ['gj', 'hk', 'il']]

where data variable is holding the value:

data = [['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['','','']
       ['q', 'r', 's'],
       ['t', 'u', 'v'],
       ['m', 'n', 'o'],
       ['','',''],
       ['g', 'h', 'i'],
       ['j', 'k', 'l']]

Upvotes: 0

Related Questions