Python convert tuple to array

Question:

How can I convert at 3-Dimensinal tuple into an array

a = []
a.append((1,2,4))
a.append((2,3,4))

in a array like:

b = [1,2,4,2,3,4]
Asked By: Samy

||

Answers:

Using list comprehension:

>>> a = []
>>> a.append((1,2,4))
>>> a.append((2,3,4))
>>> [x for xs in a for x in xs]
[1, 2, 4, 2, 3, 4]

Using itertools.chain.from_iterable:

>>> import itertools
>>> list(itertools.chain.from_iterable(a))
[1, 2, 4, 2, 3, 4]
Answered By: falsetru

If you mean array as in numpy array, you can also do:

a = []
a.append((1,2,4))
a.append((2,3,4))
a = np.array(a)
a.flatten()
Answered By: user1654183

The simple way, use extend method.

x = []
for item in a:
    x.extend(item)
Answered By: MGP
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.