【数据结构】python稀疏列表

参考

每次学数据结构都像学4级似的,永远的abandon,希望这次能坚持,参考:www.bilibili.com/video/BV1E4… 有错误麻烦提出

image.png

简单来讲就是存储的值大多数是重复,那么只需要将不是重复的值记录,其他的都是默认值即可,可以节约内存或磁盘空间

python版本实现

"""
11x11
0表示没有棋子
1表示白棋
2表示黑棋
"""
origin_list = []
for i in range(11):
    tempList = []
    for j in range(11):
        tempList.append(0)
    origin_list.append(tempList)

origin_list[0][1] = 1
origin_list[1][2] = 2
origin_list[3][4] = 2


# 转换成稀疏列表
def listToSparseList(l: list) -> list:
    # 元素不为0的个数
    num = 0
    # 稀疏数组
    sparseList = []
    for i in range(len(l)):
        for j in range(len(l)):
            if l[i][j] != 0:
                num += 1
                t = (i, j, l[i][j])
                sparseList.append(t)
    sparseList.append((11, 11, num))
    return sparseList


# 稀疏列表转换原来的列表
def sparseListToList(l: list) -> list:
    line, row, _ = l[-1]
    restore_list = []
    for i in range(line):
        tempList = []
        for j in range(row):
            tempList.append(0)
        restore_list.append(tempList)
    for i in range(len(l)-1):
        x, y, z = l[i]
        restore_list[x][y] = z
    return restore_list


# 打印原来的棋盘
for l in origin_list:
    print(l)

# 转换成稀疏列表
sparseList = listToSparseList(origin_list)
for i in sparseList:
    print(i)

# 稀疏列表转换成原来的列表
restoreList = sparseListToList(sparseList)
for l in restoreList:
    print(l)