2

I have two lists with strings which I want to concatenate elementwise into a n x n matrix. I have tried the below code but this only gives me n x 1 list.

row = ['a','b','c']
col = ['a','b','c']

matrix = map(''.join, zip(row,col))

The expected output would be a matrix like this:

[['aa','ab','ac'],
 ['ba','bb','bc'],
 ['ca','cb','cc']])

Is there a solution using either regular python or numpy to accomplish this?

Anders
  • 89
  • 9
  • Take a look at converting your list to numpy and using reshape to get it into the form you want, assuming you have the right output just in a flattened form. – JimLohse Dec 15 '19 at 21:34
  • `[[r+c for r in row] for c in col]` – Mark Dec 15 '19 at 21:35

6 Answers6

5

Regular Python - using string concatenation and list comprehension:

matrix = [[x + y for x in row] for y in col]

To be compliant with NumPy styling and the desired output use:

np.c_[matrix].T
Arn
  • 1,898
  • 12
  • 26
4

If you really want to use NumPy, you could make use of meshgrid to do something like this:

row_mat, col_mat = numpy.meshgrid(row, col)
concat_mat = numpy.core.defchararray.add(col_mat, row_mat)
erik
  • 141
  • 3
3

Here is a numpy one liner:

np.add.outer(row,col,dtype="O")
# array([['aa', 'ab', 'ac'],
#        ['ba', 'bb', 'bc'],
#        ['ca', 'cb', 'cc']], dtype=object)
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
2

For a numpy approach:

import itertools
np.array([''.join(i) for i in list(itertools.product(row,col))]).reshape(3,3)                                                                                                       

# array([['aa', 'ab', 'ac'],
#       ['ba', 'bb', 'bc'],
#       ['ca', 'cb', 'cc']], dtype='<U2')
Arn
  • 1,898
  • 12
  • 26
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
2

Taking advantage of the + definition for python strings (not numpy string dtype):

In [140]: row=np.array(['a','b','c'],object)                                    
In [141]: row[:,None]+row                                                       
Out[141]: 
array([['aa', 'ab', 'ac'],
       ['ba', 'bb', 'bc'],
       ['ca', 'cb', 'cc']], dtype=object)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

For the precise desired output

row = ['a','b','c']
col = ['a','b','c']


result = [[y + x for x in row] for y in col]
print(result)
Nuno Palma
  • 514
  • 3
  • 9