1

I have two vectors in the form

a = [[1,2,3],[1,2,3],[1,2,3]]

b = [[5,6,7],[5,6,7],[5,6,7]]

I want the output to be

c = [[1,2,3,5,6,7],[1,2,3,5,6,7],[1,2,3,5,6,7]]

I got this line

c = [[a[i],b[i]] for i in range(len(a))]

but my output is

[[[1, 2, 3], [5, 6, 7]], [[1, 2, 3], [5, 6, 7]], [[1, 2, 3], [5, 6, 7]]

3 Answers3

3

zip and concatenate each pairing:

a = [[1,2,3],[1,2,3],[1,2,3]]

b = [[5,6,7],[5,6,7],[5,6,7]]

print([i + j for i,j in zip(a, b)])

Which would give you:

[[1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7]]

Or using your own logic:

[a[i] + b[i] for i in range(len(a))]

concatenating with + is the key. If you were going to index I would use enumerate:

[ele + b[i] for i, ele in enumerate(a)]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    that's a nice way, I have several features vectors, and I need it to create an array as input for a scikit learn classifier – Jose Giraldo Oct 17 '16 at 19:29
2

Just another way:

>>> map(list.__add__, a, b)
[[1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7]]

Or using the operator module:

>>> map(operator.add, a, b)
[[1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7]]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • I'm going with padraic's solution since It could be extended to more lists in the form [ele + b[i] + c[i] for i, ele in enumerate(a)] – Jose Giraldo Oct 17 '16 at 19:38
-1

Here's a solution using the itertools module:

from itertools import chain, starmap
c = map(list, list(starmap(chain, zip(a, b))))

Edited thanks to Padraic's comment. It's too nested at this point for me to recommend using this.

Davis Yoshida
  • 1,757
  • 1
  • 10
  • 24