Dance Party2 Dance Party2 - 2 months ago 17
Python Question

Python Add Elements to Lists within List if Missing

Given the following list of lists:

a = [[2,3],[1,2,3],[1]]

I need each list within a to have the same number of elements.
First, I need to get the longest length of any list in a.
Then, I need to ensure all lists are at least that long.
If not, I want to add a zero (0) to the end until that is true.
The desired result is:

b = [[2,3,0],[1,2,3],[1,0,0]]

Thanks in advance!

P.S. I also need to apply this to a Pandas Data Frame like this one:

import pandas as pd
b = [[2,3,0],[1,2,3],[1,0,0]]


How about


enter image description here

to get exactly what you asked for


enter image description here

this is also related to this question

where you can get much better performance with

def box(v):
    lens = np.array([len(item) for item in v])
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape, 0, dtype=int)
    out[mask] = np.concatenate(v)
    return out


enter image description here

enter image description here