Python:将元组列表(可变大小)转换为具有固定形状的数组结构

时间:2021-07-19 21:44:13

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 个解决方案

#1


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

#2


2  

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

#1


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

#2


2  

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