2

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)

2 Answers 2

3
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)]
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.