Shweta
Shweta

Reputation: 1161

Python: Converting list of tuples(variable size) into array like structure with fixed shape

I have a list of tuples like:

a = [(1,2,3), (4,5)]   // np.shape = (2,)

And i want to covert it into an array like structure, but of fixed shape, ie

a = [(1,2,3), (4,5,0)] // np.shape = (2,3)

Upvotes: 2

Views: 1867

Answers (2)

thefourtheye
thefourtheye

Reputation: 239623

Functional way to do this would be

a = [(1,2,3), (4,5), (6, 7, 8, 9)]
from itertools import izip_longest
print zip(*izip_longest(*a, fillvalue = 0))
# [(1, 2, 3, 0), (4, 5, 0, 0), (6, 7, 8, 9)]

Upvotes: 3

zhangxaochen
zhangxaochen

Reputation: 34047

In [69]: maxlen=max(len(i) for i in a) #get the max length of all tuples

In [70]: [i+(0,)*(maxlen-len(i)) for i in a] #fill each tuple with extra zeros
Out[70]: [(1, 2, 3), (4, 5, 0)]

Upvotes: 3

Related Questions