Skip to content Skip to sidebar Skip to footer

Python Convert Tuple To Array

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]

Solution 1:

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]

Solution 2:

The simple way, use extend method.

x = []
for item in a:
    x.extend(item)

Solution 3:

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()

Post a Comment for "Python Convert Tuple To Array"