Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert tuple to array [duplicate]

Tags:

python

list

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]
like image 763
Samy Avatar asked Dec 17 '13 15:12

Samy


People also ask

How do you convert a tuple to an array in Python?

To convert Python tuple to array, use the np. asarray() function. The np. asarray() is a library function that converts input to an array.

Can you duplicate a tuple in Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Does tuple remove duplicates?

Method #1 : Using set() + tuple() This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple().


3 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] 
like image 200
falsetru Avatar answered Sep 21 '22 05:09

falsetru


The simple way, use extend method.

x = [] for item in a:     x.extend(item) 
like image 24
MGP Avatar answered Sep 20 '22 05:09

MGP


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()
like image 24
user1654183 Avatar answered Sep 20 '22 05:09

user1654183