给定二维列表的索引,我如何才能获得下一个项目?

时间:2016-05-22 17:43:28

标签: list python-3.x

说我有一份清单清单:

k = [[0, 1, 2],
    [0, 1, 2],
    [0, 1, 2]]

如何获取所有相邻值?例如:

鉴于

k[1][1]

它将返回:

k[0][1], k[1][0], k[1][2], k[2][1]

2 个答案:

答案 0 :(得分:0)

我有一个Astar程序,这是我使用的

get_neighbors(array,x,y):
    finalList = []
    x1_Tof, x2_Tof, y1_Tof, y2_Tof = False
    x1 = x + 1
    y1 = y + 1
    x2 = x - 1
    y2 = y - 1
    if x1 >= 0 and x1 <= len(array[0]) and y >= 0 and y <= len(array):
        x1_ToF = True
    #repeat for x2, y1, y2
    if x1_ToF == True:
        finalList.append(array[y][x1])
    #Repeat for x2_ToF...
    return finalList

P.S:记住,在python Y中首先出现!

答案 1 :(得分:0)

为了不编写真正重复的代码,您可以遍历两个维度的偏移量(在(-1, 0, 1)中),并验证每个维度的位置:

def adjacent(array,x_orig, y_orig):
    """generates all elements in 2d array around given origin"""
    for x_off in (-1,0,1):
        for y_off in (-1,0,1):
            if x_off == 0 == y_off:
                continue #when they are both 0 it is original space, skip
            x = x_orig + x_off
            y = y_orig + y_off
            if x<0 or y<0:
                continue #don't check negative indices
            try:
                yield array[x][y]
            except IndexError:
                continue #indices were out of bounds

如果您想要指定距离,这使得操作变得非常容易,例如,如果您想要获得最多2个索引的所有位置,那么您只需更改前几行:

def adjacent(array,x_orig, y_orig, possible_offsets = (-1,0,1)):
    """generates all elements in 2d array around given origin"""
    for x_off in possible_offsets:
        for y_off in possible_offsets:
            ...

然后你可以指定(-2,-1,0,1,2),它会给出适当的结果。