如何从二维数组生成一个字典?

时间:2015-11-09 13:59:24

标签: python arrays

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

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

4x4 2维列表的示例:

输入:

[[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"],
}

2 个答案:

答案 0 :(得分:0)

我相信这个算法会做

#!/usr/bin/perl
print "Content-type: text/html\n\n";
my $data_pos = tell DATA;

print $data_pos . "\n\n";
while (my $inline = <DATA>)
{
 print $inline;
}

__END__
George Washington
Abraham Lincoln
John F. Kennedy

字典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 就是你想要的

答案 1 :(得分:0)

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

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)