L=[None]
row=2
column=5
for i in range column:
print(L*row)
问题是我可以轻松创建网格。但是,我要像访问电子表格一样访问它。
例如:现在我想将第1行,第3列更改为ABC
。
赞:
原始
[None] [None]
[None] [None]
[None] [None]
[None] [None]
[None] [None]
代码更改
goto(1,3)
[None] [None]
[None] [None]
[None] [None]
[None] [----]
[None] [None]
insert(ABC)
[None] [None]
[None] [None]
[None] [None]
[None] [ABC ]
[None] [None]
现在这就是我要发生的事情。我知道如何为goto()
和insert()
创建代码,但是我不知道如何访问网格。有人可以告诉我如何访问网格吗?谢谢。
答案 0 :(得分:1)
这里您需要的是一个自定义class
,该自定义定义了方法goto
和insert
的行为类似于您刚刚描述的那样。您也可以使用全局变量和函数来完成此操作,但是使用类可以使其更易于管理和移植。
一个非常简单的实现如下:
class Spreadsheet:
def __init__(self, rows, columns):
self.matrix = []
self.rows = rows
self.columns = columns
self.cur_pos = (0, 0)
for i in range(rows):
self.matrix.append([])
for j in range(columns):
self.matrix[i].append(None)
def goto(self, x, y):
if 0 <= x < self.rows and 0 <= y < self.columns:
self.cur_pos = (x, y)
else:
raise Exception('Cannot goto({},{}): matrix indexes out of range!'.format(x, y))
def insert(self, element):
self.matrix[self.cur_pos[0]][self.cur_pos[1]] = element
然后您可以像这样使用它:
s = Spreadsheet(5, 2)
s.goto(3, 1)
s.insert('ABC')
for line in s.matrix:
print(line)
结果将是:
[None, None]
[None, None]
[None, None]
[None, 'ABC']
[None, None]