Python 更改嵌套列表中的整数
给定 然后,set函数应按如下方式更改矩阵Python 更改嵌套列表中的整数,python,Python,给定 然后,set函数应按如下方式更改矩阵 test_case_100 = make_matrix([[32, 33], [50, 92]]) # [[32, 33], [50, 92]] 正如@thefourtheye在评论中指出的那样,你让这件事变得比应该的要困难得多 set(test_case_100, 2, 2, 50) # [[32, 33], [50, 50]] set(test_case_100, 2, 1, 30) #[[32, 33], [30, 50]] set(test
test_case_100 = make_matrix([[32, 33], [50, 92]]) # [[32, 33], [50, 92]]
正如@thefourtheye在评论中指出的那样,你让这件事变得比应该的要困难得多
set(test_case_100, 2, 2, 50) # [[32, 33], [50, 50]]
set(test_case_100, 2, 1, 30) #[[32, 33], [30, 50]]
set(test_case_100, 1, 2, 29) #[[32, 29], [30, 50]]
set(test_case_100, 1, 1, -20) #[[-20, 29], [30, 50]]
print(set(test_case_100, 2, 2, 50)) # [[-20, 29], [30, 50]]
这可能是将OOP引入您的编码风格的好时机
def set_matrix(matrix, row, col, value):
try:
matrix[row-1][col-1] = value
except IndexError:
raise IndexError("No value at x:{}, y:{}".format(row,col))
在这里使用新类的原因是,您可以做一些很酷的事情,例如:
class Matrix(list):
def __init__(self, *args):
for arg in args:
self.append(arg)
def setval(self,row,col,value):
try:
self[row-1][col-1] = value
except IndexError:
raise IndexError("No value at x:{}, y:{}".format(row,col))
test_matrix = Matrix([32, 33], [50, 92])
test_matrix.setval(2,2,50)
print(test_matrix) # [[32, 33], [50, 50]]
请不要命名此
def集
,它会隐藏内置集
的构造函数。此外,请为变量命名一些有用的名称!什么是m
,i
或j
?那么x
、y
、z
、a
或者b
呢???完全没有意义为什么你不简单地做m[i-1][j-1]=val
@我之前想到过这个,但之后我该怎么办?@user3398505什么?我没有收到你的问题我还是要删除和插入对吗?
class Matrix(list):
def __init__(self, *args):
for arg in args:
self.append(arg)
def setval(self,row,col,value):
try:
self[row-1][col-1] = value
except IndexError:
raise IndexError("No value at x:{}, y:{}".format(row,col))
test_matrix = Matrix([32, 33], [50, 92])
test_matrix.setval(2,2,50)
print(test_matrix) # [[32, 33], [50, 50]]
class Matrix(list):
# code goes here
def __str__(self):
COLSIZE = max(map(len,(val for col in self for val in col)))+1
NUMCOLS = len(self[0]) # all rows equal size I hope!
formatstring = "{}{}{}".format("{:>",COLSIZE,"}")*NUMCOLS
return "\n".join(formatstring.format(*row) for row in self)
>>> print(Matrix([1,2],[3,4],[5,6]))
1 2
3 4
5 6
>>> print(Matrix([226,1],[330,1000],[15,17]))
226 1
330 1000
15 17