1

say I have a matrix : a = [[1,2,3],[4,5,6],[7,8,9]]. How can I combine it to b = [1,2,3,4,5,6,7,8,9]?

Many thanks

J_yang
  • 2,672
  • 8
  • 32
  • 61
  • 1
    `b = numpy.hstack(a)` –  Mar 18 '19 at 22:18
  • 1
    `import itertools; list(itertools.chain(*a))` – solarc Mar 18 '19 at 22:21
  • Possible duplicate of [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists), [Flattening a shallow list in Python \[duplicate\]](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python), [concatenating sublists python \[duplicate\]](https://stackoverflow.com/questions/17142101/concatenating-sublists-python), etc. – chickity china chinese chicken Mar 18 '19 at 22:24
  • Duplicate of [how-to-unnest-a-nested-list](https://stackoverflow.com/questions/11860476/how-to-unnest-a-nested-list) – Will Mar 18 '19 at 22:42
  • Is `a` a list of lists or a numpy array? Why the numpy tag? – hpaulj Mar 18 '19 at 23:45

5 Answers5

2

Using numpy:

import numpy
a = [[1,2,3],[4,5,6],[7,8,9]]
b = numpy.hstack(a)
list(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Istvan
  • 7,500
  • 9
  • 59
  • 109
0

Maybe this is not the most beautiful, but it works:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [sub_thing for thing in a for sub_thing in thing]
print(b)

Prints:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Reedinationer
  • 5,661
  • 1
  • 12
  • 33
0

Without using numpy:

#make the empty list b
b=[]
for row in a:#go trough the matrix a
    for value in row: #for every value
        b.append(value) #python is fun and easy
0

Another way to combine integer matrix could be using the itertools chain.

a = [[1,2,3],[4,5,6],[7,8,9]]
list(itertools.chain.from_iterable(a)

prints:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

julian salas
  • 3,714
  • 1
  • 19
  • 20
0

using numpy:

list(np.array(a).flatten())

Joanne
  • 1
  • 1