【问题标题】:How to generate a dict from an 2 dimensional array? [closed]如何从二维数组生成字典? [关闭]
【发布时间】:2016-02-10 04:44:53
【问题描述】:

我想从二维列表生成字典。

字典的key应该是数组位置(x,y)的索引。该值应该是包含此数组位置的所有邻居(上、下、右、左)的列表。该值是邻居的位置。

4x4 二维列表示例:

输入:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

输出:

graph = {
    '0,0': ["0,1", "1,0"],
    '0,1': ["0,0", "1,1", "0,2"],
    '0,2': ["0,1", "0,3", "1,2"],
    '0,3': ["0,2", "1,3"],

    '1,0': ["0,0", "1,1", "2,0"],
    '1,1': ["0,1", "1,0", "2,1", "1,2"],
    '1,2': ["0,2", "1,1", "2,2", "1,3"],
    '1,3': ["0,3", "1,2", "2,3"],

    '2,0': ["1,0", "3,0", "2,1"],
    '2,1': ["2,0", "3,1", "2,2", "1,1"],
    '2,2': ["1,2", "2,1", "3,2", "2,3"],
    '2,3': ["1,3", "2,2", "3,3"],

    '3,0': ["2,0", "3,1"],
    '3,1': ["2,1", "3,0", "3,2"],
    '3,2': ["2,2", "3,1", "3,3"],
    '3,3': ["2,3", "3,2"],
}

【问题讨论】:

  • 那么您尝试了哪些方法,究竟有什么问题?
  • 我认为可能有一个简单的解决方案,但我找不到任何人。
  • ... “那么你尝试了什么,它到底有什么问题?”如果你有你认为的工作代码可以改进,请参阅Code Review。如果你没有代码,那就写一些吧。

标签: python arrays


【解决方案1】:

我相信这个算法会做

grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] #input

dic = dict()
for i in xrange(len(grid)):
    for j in xrange(len(grid[0])):
        x = []
        for k in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
            if 0 <= i + k[0] < len(grid) and 0 <= j + k[1] < len(grid[0]):
                x.append((i + k[0], j + k[1]))
        dic[(i, j)] = x

字典dic是你想要的

【讨论】:

  • 哦,列表中的最后一个条目是错误的!
【解决方案2】:

现在这对我有用。我愿意接受任何改进。

size_y = 4
size_x = 4

l = [[0 for x in range(size_y)] for x in range(size_x)]
d = {}

for x in range(size_x):
    for y in range(size_y):
        key = "{},{}".format(x, y)
        # edges
        if x == 0 and y == 0:
            l = ["0,1", "1,0"]
        elif x == size_x-1 and y == size_y-1:
            l = ["{},{}".format(x,y-1), "{},{}".format(x-1,y)]
        elif x == size_x-1 and y == 0:
            l = ["{},{}".format(x-1,y),"{},{}".format(x,y+1)]
        elif x == 0 and y == size_y-1:
            l = ["{},{}".format(0,y-1),"{},{}".format(x+1,y)]
        else:
            l = []
            #N x y-1
            if y-1 >= 0:
                l.append("{},{}".format(x, y-1))
            #O x+1 y
            if x+1 < size_x:
                l.append("{},{}".format(x+1, y))
            #S x y+1
            if y+1 < size_y:
                l.append("{},{}".format(x, y+1))
            #W x-1 y
            if x-1 >= 0:
                l.append("{},{}".format(x-1, y))
        d[key] = l

print(d)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多