The Python Oracle

Python Add Elements to Lists within List if Missing

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Python Add Elements To Lists Within List If Missing
00:36 Answer 1 Score 5
01:18 Answer 2 Score 0
01:24 Accepted Answer Score 5
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/4064...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #pandas #numpy

#avk47



ANSWER 1

Score 5


First, compute the maximum length of your elements:

maxlen=len(max(a,key=len))  # max element using sublist len criterion

or as Patrick suggested do it using generator comprehension on sublist lengths, probably a tad faster:

maxlen=max(len(sublist) for sublist in a)  # max of all sublist lengths

then create a new list with 0 padding:

b = [sl+[0]*(maxlen-len(sl)) for sl in a]  # list comp for padding

result with a = [[2,3],[1,2,3],[1]]:

[[2, 3, 0], [1, 2, 3], [1, 0, 0]]

Note: could be done in one line but would not be very performant because of the recomputation of maxlen. One-liners are not always the best solution.

b = [sl+[0]*(len(max(a,key=len))-len(sl)) for sl in a]  # not very performant



ACCEPTED ANSWER

Score 5


How about

pd.DataFrame(a).fillna(0)

enter image description here


to get exactly what you asked for

pd.Series(pd.DataFrame(a).fillna(0).astype(int).values.tolist()).to_frame('column')

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

pd.DataFrame(dict(columns=box(a).tolist()))

enter image description here


timing
enter image description here




ANSWER 3

Score 0


for i in a: 
    while len(i) < 3:
        i.append(0)