Say I have a 3D list in Python, but it's severely jagged:
old_list = [[[0, 1, 2],
[3, 4, 5, 6],
[7, 8]],
[[9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18],
[19, 20, 21, 22]],
[[23, 24, 25],
[26, 27]]]
I need to "regularize" it so that it still has the same elements, but with 0
being used to fill in any gaps in the jagged parts. I'm aiming for something like this, which is 3x4x5:
new_list = [[[0, 1, 2, 0, 0],
[3, 4, 5, 6, 0],
[7, 8, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[9, 10, 0, 0, 0],
[11, 12, 13, 14, 15],
[16, 17, 18, 0, 0],
[19, 20, 21, 22, 0]],
[[23, 24, 25, 0, 0],
[26, 27, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]]
Is there an efficient algorithm to do this for any number of dimensions? And better yet, without importing anything?
UPDATE 1:
The answers I've been getting are pretty okay, but not good enough for my purpose. I'm sorry. But I just found a way to solve my problem! I need to do a little more coding, though. Thanks for the answers!
UPDATE 2:
BINGO! No need to answer anymore - I got this.