这并不能回答您的图形问题,但您肯定可以在Python中实现2D列表,而不必以至少两种方式求助于列表列表:
你可以简单地使用字典:import collections
t = collections.defaultdict(int)
t[0, 5] = 9
print t[0, 5]
这也有一个优点,那就是它是稀疏的。
对于更奇特的方法,但需要更多的工作,您可以使用1d列表并使用二维坐标以及表的高度和宽度计算索引。class Table(object):
def __init__(self, width, height):
self._table = [None,] * (width * height)
self._width = width
def __getitem__(self, coordinate):
if coordinate[0] >= width or coordinate[1] >= height:
raise IndexError('Index exceeded table dimensions')
if coordinate[0] < 0 or coordinate[1] < 0:
raise IndexError('Index must be non-negative')
return self._table[coordinate[1] * width + coordinate[0]]
def __setitem__(self, coordinate, value):
if coordinate[0] >= width or coordinate[1] >= height:
raise IndexError('Index exceeded table dimensions')
if coordinate[0] < 0 or coordinate[1] < 0:
raise IndexError('Index must be non-negative')
self._table[coordinate[1] * width + coordinate[0]] = value
t = Table(10,10)
t[0, 5] = 9
print t[0, 5]