I have some python code that I wrote to convert a python list into an XML element. It\'s meant for interacting with LabVIEW, hence the weird XML array format. Anyways, here\
Try the following:
from operator import mul
def validate(array, sizes):
if reduce(mul, sizes) != len(array):
raise ValueError("Array dimension incompatible with desired sizes")
return array, sizes
def reshape(array, sizes):
for s in sizes:
array = [array[i:i + s] for i in range(0, len(array), s)]
return array[0]
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
length = [2, 2, 3]
print reshape(validate(data, length))
length = [2, 2, 2]
print reshape(validate(data, length))
Output being:
[[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
Traceback:
(...)
ValueError: Array dimension incompatible with desired sizes
An alternative is using numpy
arrays. Note that for this simple task, numpy is a rather big dependency, though you will find that most (common) array related tasks/problems already have an implementation there:
from numpy import array
print array(data).reshape(*length) # optionally add .tolist() to convert to list
EDIT: Added data validation
EDIT: Example using numpy arrays (thanks to J.F.Sebastian for the hint)