Python电子表格,创建一个可访问的列表网格

2024-06-26 14:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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()创建代码,但我不知道如何访问网格。有人能告诉我如何进入电网吗?多谢各位


Tags: 代码innone网格forrangecolumn电网
1条回答
网友
1楼 · 发布于 2024-06-26 14:25:50

这里需要的是一个自定义的class,它定义了方法gotoinsert,使它们的行为与您刚才描述的一样。您也可以使用全局变量和函数来实现这一点,但使用类可以使其更易于管理和移植

一个非常简单的实现如下所示:

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]

相关问题 更多 >