Python:从矩阵的行和列中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36575328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: get value from row and column from a matrix
提问by jnmf
I'm learning how to code and I didn't quite understand how a class really works. If I create a matrix for example:
我正在学习如何编码,但我不太了解类的实际工作原理。例如,如果我创建一个矩阵:
class Matrix(object):
def __init__(self,i,j,value):
self.rows = i
self.cols = j
self.value = value
if I have a random matrix and want to select the biggest value in a row, i can write:
如果我有一个随机矩阵并想选择一行中的最大值,我可以写:
for value in row
and the program will know I mean the value ij in the ith row?
程序会知道我的意思是第 i 行中的值 ij 吗?
回答by niklas
Usually in python Matrixes would be two dimensional arrays. Like:
通常在 python 矩阵中是二维数组。喜欢:
matrix = [[11,12,13,14],[21,22,23,24],[31,32,33,34]]
//is the same as
//是相同的
would give you a matrix like:
会给你一个矩阵,如:
11 12 13 14
21 22 23 24
31 32 33 34
so you have an array which stores the rows (the outer array) and one array for each row. To access e.g. the value at position (2,4) which is 24
you would do
所以你有一个数组来存储行(外部数组)和每行一个数组。要访问例如位置 (2,4) 处的值,24
您会这样做
matrix[1][3]
as matrix[1] = [21,22,23,24]
and matrix[1][3] = [21,22,23,24][3] = 24
作为matrix[1] = [21,22,23,24]
和matrix[1][3] = [21,22,23,24][3] = 24
To iterate over your matrix (i.e. your two dimensional array) you can do:
要迭代您的矩阵(即您的二维数组),您可以执行以下操作:
#iterate over the rows
for row in matrix:
#max value
max = max(row)
print max
#if you want to iterate over the elements in the row do:
for element in row:
print element
In Your example you are defining a Matrix class which will be initialized with 3 parameters: i
, j
and value
. You are not doing more. For examples of your own matrix class you could have a look here
在您的示例中,您正在定义一个 Matrix 类,该类将使用 3 个参数进行初始化:i
,j
和value
。你没有做更多。有关您自己的矩阵类的示例,您可以查看此处
回答by knh170
Use enumerateto interpolate indexes:
使用enumerate插入索引:
>>> for i, j in enumerate(["a","b","c"]):
... print i, j
...
0 a
1 b
2 c
In your case:
在你的情况下:
# suppose m is an instance of class Matrix
for i, row in enumerate(m.value):
for j, ele in enumerate(row):
# find greatest and halt
# i, j are the expected index
yeild i, j
To find a largest element from a list there are multiple ways, for example: Pythonic way to find maximum value and its index in a list?
要从列表中查找最大元素,有多种方法,例如:Pythonic 方法来查找列表中的最大值及其索引?
However, more clever way is to utilize numpy.matrixif programming yourself is not necessary.
但是,如果不需要自己编程,更聪明的方法是使用numpy.matrix。
回答by Vini.g.fer
The
这
for value in row
code will NOT get you the biggest value in the row. It will just iterate (run through) each item in the row (once you define row of course). You need to add a check to get the biggest number.
代码不会让您获得该行中的最大价值。它只会迭代(运行)行中的每个项目(当然,一旦您定义了行)。您需要添加一个支票以获得最大的数字。