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]]
How can I change the parameters so I can get a 5x5 matrix?
如何更改参数才能获得5x5矩阵?
更多回答
What are you trying to do here? Do you want a matrix that you can access matrix[row][column]
to get elements from it? Do you want to populate the matrix with some information? Right now you have nested lists such that you can access elements inside (and retrieve a certain "inf") using matrix[row][column]
(depending on how you look at it) to access a particular element, it's just printed out all in one line.
你在这里想做什么?是否需要一个可以访问矩阵[行][列]以从中获取元素的矩阵?是否要在矩阵中填充一些信息?现在您有嵌套的列表,这样您就可以使用矩阵[行][列](取决于您如何看待它)来访问其中的元素(并检索特定的“inf”)来访问特定的元素,它只在一行中打印出来。
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:
您已经拥有的是一个5x5矩阵。仅表示为行的列表。如果你想要一个看起来像矩阵的东西,也许你会喜欢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]])
This is Simplest way I Found to Create
5x5 matrix with row values ranging from 0 to 4
这是我发现的创建行值从0到4的5x5矩阵的最简单方法
arr = np.arange(0,5)
arr = np.tile(arr,(5,1))
arr
import numpy as np
将Numpy导入为NP
x = np.arange(0,5).reshape(5,1)
X=np.arange(0,5).重塑(5,1)
print(x)
打印(X)
更多回答
I was trying to show why they didn't need to use range(len(lst))
and how to access elements in the "matrix".
我试图说明为什么他们不需要使用range(len(Lst)),以及如何访问“矩阵”中的元素。
Is that answer correct to solve the question Create a 5x5 matrix with row values ranging from 0 to 4.
对于创建行值范围从0到4 5x5矩阵的问题,答案正确吗?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
正如它目前所写的,你的答案并不清楚。请编辑以添加更多详细信息,以帮助其他人了解这是如何解决提出的问题的。你可以在帮助中心找到更多关于如何写出好答案的信息。
我是一名优秀的程序员,十分优秀!