Putting Incomplete Nested Lists In A Rectangular Ndarray
In Python (also using numpy) I have a list of lists of lists, with each list being different lengths. [ [ ['header1','header2'], ['---'], [],
Solution 1:
You can create a ndarray
with the desired dimensions and readily read your list. Since your list is incomplete you must catch the IndexError
, which can be done in a try / exception
block.
Using numpy.ndenumerate
allows the solution to be easily extensible to more dimensions (adding more indexes i,j,k,l,m,n,...
in the for loop below):
import numpy as np
test = [ [ ["header1","header2"],
["---"],
[],
["item1","value1"] ],
[ ["header1","header2","header3"],
["item2","value2"],
["item3","value3","value4","value5"] ] ]
collector = np.empty((2,4,4),dtype='|S20')
for (i,j,k), v in np.ndenumerate( collector ):
try:
collector[i,j,k] = test[i][j][k]
except IndexError:
collector[i,j,k] = ''
print collector
#array([[['header1', 'header2', '', ''],
# ['---', '', '', ''],
# ['', '', '', ''],
# ['item1', 'value1', '', '']],
# [['header1', 'header2', 'header3', ''],
# ['item2', 'value2', '', ''],
# ['item3', 'value3', 'value4', 'value5'],
# ['', '', '', '']]], dtype='|S10')
Post a Comment for "Putting Incomplete Nested Lists In A Rectangular Ndarray"