This does not answer your question in the graph, but you can certainly implement a 2D list in Python without resorting to list lists in at least two ways:
You can simply use the dictionary:
import collections t = collections.defaultdict(int) t[0, 5] = 9 print t[0, 5]
It also has the advantage of being sparse.
For a more convenient approach, but requiring more work, you can use the 1d list and calculate the index using 2D coordinates, as well as the height and width of the table.
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]
source share