skidzo
skidzo

Reputation: 415

Concatenate rows of two dimensional list elements in a list

I want to reorganize two-dimensional list elements in a list (here two elements):

[[['A','B','C'], 
  ['G','H','I']], 
 [['D','E','F'], 
  ['J','K','L']]]

to become:

[['A','B','C','D','E','F'], 
 ['G','H','I','J','K','L']]

Is there a better way to write this, than the one expressed by the following function?

def joinTableColumns(tableColumns):
    """
    fun([[['A','B','C'], 
          ['G','H','I'] ], 
         [['D','E','F'], 
          ['J', 'K', 'L']]]) --> [['A', 'B', 'C', 'D', 'E', 'F'], 
                                  ['G', 'H', 'I', 'J', 'K', 'L']]
    """
    tableData = []

    for i,tcol in enumerate(tableColumns):

        for j,line in enumerate(tcol):
            if i == 0:
                tableData.append(line)
            else:
                tableData[j]+=line

    return tableData

Considering, that the number of rows to join is equal:

tdim_test = [(len(x), [len(y) for y in x][0] )for x in tableData]

len(list(set([x[0] for x in tdim_test])))==1

How can I increase robustness of that function? Or, is there something from a standard library that I should use instead?

Upvotes: 2

Views: 100

Answers (3)

Hans Peter Hagblom
Hans Peter Hagblom

Reputation: 88

import functools
[ functools.reduce(lambda x,y: x + y, i,[])  for i in zip(*matrix)]

This will give you what you want

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107297

Yes, you can use zip() function and itertools.chain() within a list comprehension:

In [17]: lst = [[['A','B','C'], 
                 ['G','H','I']], 
                [['D','E','F'], 
                 ['J','K','L']]]

In [18]: from itertools import chain

In [19]: [list(chain.from_iterable(i)) for i in zip(*lst)]
Out[19]: [['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L']]

Or as a pure functional approach you can use itertools.starmap() and operator.add():

In [22]: from itertools import starmap

In [23]: from operator import add

In [24]: list(starmap(add, zip(*lst)))
Out[24]: [['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L']]

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160447

You could just use the zip function, unpacking the table inside it and add the pairs:

table = [[['A','B','C'], ['G','H','I']], 
         [['D','E','F'], ['J','K','L']]]    
res = [t1 + t2 for t1, t2 in zip(*table)]

which yields your wanted result:

[['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L']]

Upvotes: 0

Related Questions