[英]How to construct a 5x5 matrix?
How can I construct a matrix with 5 rows and 5 columns? 如何构建一个包含5行和5列的矩阵?
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]]
给我
[[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? 如何更改参数以便获得5x5矩阵?
I'm not sure why you are using the lst
variable, but what you need is something approaching this: 我不确定你为什么使用
lst
变量,但你需要的是接近这个的东西:
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. 你已经拥有的是 5x5矩阵。 Just represented as a list of rows.
只表示为行列表。 If you want something that "looks" like a matrix, maybe you'll like numpy:
如果你想要一些“看起来”像矩阵的东西,也许你会喜欢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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.