如何在多维数组中找到特定值?

时间:2016-05-23 03:41:27

标签: python multidimensional-array

我正在制作一个像棋子一样的游戏,创建我使用多维数组的棋盘。我在每个空白区域填充0的数组,然后一组芯片用1表示,另一组用2表示。有什么方法可以让我得到每组芯片占用空间的列表?这是我的游戏板:

matrix = [[1,1,1,1,1,0,0,0,0,0], [1,1,1,1,0,0,0,0,0,0],
          [1,1,1,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0],
          [1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2],
          [0,0,0,0,0,0,0,0,2,2], [0,0,0,0,0,0,0,2,2,2],
          [0,0,0,0,0,0,2,2,2,2], [0,0,0,0,0,2,2,2,2,2]]

print "\n".join(" ".join(str(el) for el in row) for row in matrix)

2 个答案:

答案 0 :(得分:4)

你可以使用list comprehension with condition,下面的代码返回2占用的所有空格:

[(y, x) for y in xrange(len(matrix)) for x in xrange(len(matrix[y])) if matrix[y][x] == 2]

输出:

[(5, 9), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 6), (8, 7), (8, 8), (8, 9), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)]

答案 1 :(得分:0)

虽然列表推导通常是构建单个列表的好方法,但您必须多次遍历整个矩阵才能找到每个可能芯片值的位置。或者,您可以通过执行以下操作,通过矩阵创建每种芯片占用哪些空间的列表:

matrix = [[1,1,1,1,1,0,0,0,0,0], [1,1,1,1,0,0,0,0,0,0],
          [1,1,1,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0],
          [1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2],
          [0,0,0,0,0,0,0,0,2,2], [0,0,0,0,0,0,0,2,2,2],
          [0,0,0,0,0,0,2,2,2,2], [0,0,0,0,0,2,2,2,2,2]]

positions = {}
for y in xrange(len(matrix)):
    for x in xrange(len(matrix)):
        positions.setdefault(matrix[y][x], []).append((y, x))

# show the all positions of each chip value
for chip in sorted(positions):
    print('{}: {}'.format(chip, positions[chip]))

输出:

0: [(0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4)]
1: [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]                                                                                                                                                                                                                                                                                                                                                                                                                                                        
2: [(5, 9), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 6), (8, 7), (8, 8), (8, 9), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)]