Say I have an array of the shape:
import numpy as np
a = np.zeros(shape=(3, 4, 2))
which looks like:
print a
[[[ 0. 0.]
[ 0. 0.]
[ 0. 0.]
[ 0. 0.]]
[[ 0. 0.]
[ 0. 0.]
[ 0. 0.]
[ 0. 0.]]
[[ 0. 0.]
[ 0. 0.]
[ 0. 0.]
[ 0. 0.]]]
How do I create an empty list with the same shape, where every 0.
element is replaced by an empty sub-list?
In the specific case shown above, it would look like:
[[[[], []]
[[], []]
[[], []]
[[], []]],
[[[], []]
[[], []]
[[], []]
[[], []]],
[[[], []]
[[], []]
[[], []]
[[], []]]]
but I need a way that works in general for arrays of any shape. Is there a built in function to do this?
np.empty(shape=(3, 4, 2, 0))
might be what you are looking for. Or more generally, np.empty(shape=your_shape+(0,))
where your_shape is a tuple like (3, 4, 2)
.
Now to get the desired list of lists, you can call the tolist method:
np.empty(shape=your_shape+(0,)).tolist()
Otherwhise, you could do a wrapper function that returns nested list comprehensions:
a = [[[[] for j in range(2)] for i in range(4)] for k in range(3)]
and if you want a numpy array:
a = np.array(a)
Such a function could be:
import copy
def empty(shape):
if len(shape) == 1:
return [[] for i in range(shape[0])]
items = shape[0]
newshape = shape[1:]
sublist = empty(newshape)
return [copy.deepcopy(sublist) for i in range(items)]
and you would call it like this:
a = empty([3,4,2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With