那样做是行不通的。
实际上,我有点撒谎。它会这样工作(我对你写的生成器有问题):
>>> table = [[raw_input('Input data: ') for i in range(1, nc+1)] for i in range(1, nr+1)]
Input data: 1
Input data: 2
Input data: 3
Input data: 4
Input data: 5
Input data: 6
Input data: 7
Input data: 8
Input data: 9
>>> table
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
但这正是您一开始所要求的——您似乎希望最终用户能够输入列标题和行标题,然后填充数据。
如果我们:
table = [[raw_input('Input data: {},{} '.format(a,b)) for a in range(0, nc)] for b in range(0, nr)]
那么我们可以得到:
Input data: 0,0 None
Input data: 1,0 1
Input data: 2,0 2
Input data: 0,1 a
Input data: 1,1 Ted
Input data: 2,1 Fred
Input data: 0,2 b
Input data: 1,2 3.214
Input data: 2,2 Copy
>>> table
[['None', '1', '2'], ['a', 'Ted', 'Fred'], ['b', '3.214', 'Copy']]
现在,您的方案中混乱的部分是,要在“网格”中找到坐标,您必须读取每个列标题并取回它的位置,然后读取每一行标题以取回 它是 em>位置。那么你可以:
值 = 网格[r][c]
现在,逆向操作更加困难——您必须阅读每个单元格才能取回行标题和列标题。
哦,我们没有进行任何错误检查,以确保您输入的 2 行或标题不一样,这会彻底破坏您的计划。你会需要那个。
此外,填写该网格需要大量工作。
剩下的就是我在没有生成器的情况下胡思乱想,并犯了一些教育错误。
如果你想使用列表列表:
row = [None for i in range(0,nc+1)]
grid = [row for i in range(0,nr+1)]
然后,这会为您提供一个列表,其中包含无填充的列表。
>>> grid
[[None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]]
好的,所以输入列标题:
>>> for ch in range (1,nc+1):
... grid[0][ch] = raw_input("Header, Column {}".format(ch))
...
Header, Column 111
Header, Column 222
Header, Column 333
>>> grid
[[None, '11', '22', '33'], [None, '11', '22', '33'], [None, '11', '22', '33'], [None, '11', '22', '33']]
咦,怎么没用?
>>> grid[0][3]="steve"
>>> grid
[[None, '11', '22', 'steve'], [None, '11', '22', 'steve'], [None, '11', '22', 'steve'], [None, '11', '22', 'steve']]
哦,是的。
臭虫。
import copy
row = [None for i in range(0,nc+1)]
grid = [copy.deepcopy(row) for i in range(0,nr+1)]
>>> for ch in range (1,nc+1):
... grid[0][ch] = raw_input("Header, Column {}: ".format(ch))
...
Header, Column 1: 11
Header, Column 2: 22
Header, Column 3: 33
>>> grid
[[None, '11', '22', '33'], [None, 5, None, None], [None, None, None, None], [None, None, None, None]]
(忽略5,那是我测试的)
然后是行:
>>> for rh in range(1,nr+1):
... grid[rh][0] = raw_input("Row Header: {} ".format(rh))
...
Row Header: 1 11
Row Header: 2 22
Row Header: 3 33
>>> grid
[[None, '11', '22', '33'], ['11', 5, None, None], ['22', None, None, None], ['33', None, None, None]]
所以现在你用数据填充它(留作练习,因为它很明显)。