python构建有向图_用python实现有向图

这并不能回答您的图形问题,但您肯定可以在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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值