Padding a list within list

Hello

I have a list of indexes within a list like below :

([[40, 3], [41, 3], [30, 3], [31, 3]],
[[30, 3], [40, 3], [50, 3], [43, 5]],
[[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]],
[[60, 4], [70, 4]])

I want to pad it with torch.zeros of size 2 with the maximum sequence lengthin the list (max seq length is 5 i.e.([[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]]):

([[40, 3], [41, 3], [30, 3], [31, 3], [0,0]],
[[30, 3], [40, 3], [50, 3], [43, 5], [0,0]],
[[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]],
[[60, 4], [70, 4], [0,0], [0,0], [0,0]])

Any suggestions will be appreciated.

>>> n = np.max([len(item) for item in a])
>>> a_paded = [item + [[0,0]]*(n-len(item)) if len(item) < n else item for item in a]
>>> a_paded
[[[40, 3], [41, 3], [30, 3], [31, 3], [0, 0]], 
 [[30, 3], [40, 3], [50, 3], [43, 5], [0, 0]], 
 [[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]], 
 [[60, 4], [70, 4], [0, 0], [0, 0], [0, 0]]]
2 Likes

may be the for-loop is what you need…

a = ([[40, 3], [41, 3], [30, 3], [31, 3]],
[[30, 3], [40, 3], [50, 3], [43, 5]],
[[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]],
[[60, 4], [70, 4]])

for ele in a:
    for i in range(5-len(ele)):
        ele.append([0, 0])

print(a)

you will get

([[40, 3], [41, 3], [30, 3], [31, 3], [0, 0]],
 [[30, 3], [40, 3], [50, 3], [43, 5], [0, 0]],
 [[12, 3], [30, 3], [31, 3], [17, 3], [27, 3]],
 [[60, 4], [70, 4], [0, 0], [0, 0], [0, 0]])

1 Like