Reputation: 13
Important context: Dig on the esolang wiki
I am making an compiler for a esoteric programming language, using a 2d list to account for the language’s 2d nature. The problem comes when I need all the lists in the one mega list to be of same length.
This:
[[“#”,”#”],[“#”,”#”,”#”]]
Needs be this:
[[“#”,”#”,” “],[“#”,”#”,”#”]]
Thanks!
Upvotes: 0
Views: 431
Reputation: 71454
>>> mega_list = [["#","#"],["#","#","#"]]
>>> for a in mega_list:
... a.extend([" "] * (max(map(len, mega_list)) - len(a)))
...
>>> mega_list
[['#', '#', ' '], ['#', '#', '#']]
Upvotes: 1
Reputation: 7510
You can do it like this, finding the max length of the lists first:
max_length = max( len(i) for i in l)
[ i + [" "]*(max_length-len(i)) for i in l ]
Upvotes: 0
Reputation: 3294
To apply fillvalues to uneven lists, use the itertools.zip_longest function.
import itertools as it
lists = [[1,2,3],[4,5]]
lists = list(zip(*it.zip_longest(*lists,fillvalue=' ')))
print(lists)
Upvotes: 1