Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

standard python library to construct matrix

Tags:

python

matrix

What is the easiest way to construct a zeros matrix with a cardinality of 1000 (row) x 10 (column) in Python without using numpy? (just the standard library)

Also, say if I get a list of values with 10 elements. say a=[1 2 3 ... 10], and I would like overwrite the 1st row of the zeros matrix with this list a. How would I go about doing it.

Many thanks.

PS: the reason that I would like to use the normal python list rather than numpy to construct the matrix is because of the requirement of this assignment, which does not allow any external libraries other than the python standard lib.

like image 714
C. Zeng Avatar asked Oct 24 '25 18:10

C. Zeng


1 Answers

You can do:

m = [[0 for _ in range(10)] for _ in range(1000)]
m[0] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that if you use:

>>> matrix = 3*[3*[0]]
>>> matrix 
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

after changing one element:

>>> matrix[0][0] = 1
>>> matrix
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

the whole column will change. So you should use this method only if you don't need your elements to be able to change independently.

like image 81
elyase Avatar answered Oct 27 '25 07:10

elyase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!