My objective is to create the following table (2D vector of namedtuples) in python:
(0,0,1) | (2,0,7) | (1,0,1)
| (3,0,1) | (4,0,1)
| (5,0,1) |
As can be seen, table T[0] is of size 1, T[1] is of size 3 and T[2] of size 2.
All approches I have seen so far relate to the use List Comprehension but that results in a fixed MxN matrix. I am curious to know if I can use python to first pre-allocate the size of first-dimension (in my case 3) and then keep appending elements to each T[i].
While writing in C++, I would declared a vector T of size 3 and continue to push_back elements to each dimension as need be in a dynamic fashion. However I am unable to find an elegant way to write this is python.
I am very new to python and my first attempt was to do the following (without the use of namedtuples):
T=[]
arr1=[0,1,2]
arr2=[3,4]
arr3=[6,6,7,8]
T.append(arr1)
T.append(arr2)
T.append(arr3)
This led to the following result:
>>T
[[0, 1, 2], [3, 4], [5, 6, 7, 8]]
However if I clear arr1, it shall be removed from T as well. Is there a better approach to this problem?
When you append arr1 to T, you are not making a new copy of the arr1 list. You need to make a copy of the list before you append it to T so that when you modify arr1, the list that you added to T is not modified.
To do this, use T.append(list(arr1)). That will make a new copy of arr1 before adding it to T.
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