How can I construct a matrix with 5 rows and 5 columns?
lst = [1,2,3,4,5]
[[float("inf")]*len(lst) for k in range (len(lst))]
gives me [[inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf]]
How can I change the parameters so I can get a 5x5 matrix?
I'm not sure why you are using the lst
variable, but what you need is something approaching this:
def matrix(x,y,initial):
return [[initial for i in range(x)] for j in range(y)]
Which gives:
> print matrix(5,5,float('inf'))
[[inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf], [inf, inf, inf, inf, inf]]
> my_matrix = matrix(2,2,0)
> print my_matrix
[[0, 0], [0, 0]]
> my_matrix[0][2] = 2
> print my_matrix
[[0, 2], [0, 0]]
A matrix in most languages is just a set of nested arrays. If you need anything more than that you might want to make a custom class.
What you have already is a 5x5 matrix. Just represented as a list of rows. If you want something that "looks" like a matrix, maybe you'll like numpy:
>>> import numpy as np
>>> np.full((5, 5), np.inf)
array([[ inf, inf, inf, inf, inf],
[ inf, inf, inf, inf, inf],
[ inf, inf, inf, inf, inf],
[ inf, inf, inf, inf, inf],
[ inf, inf, inf, inf, inf]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.