在列表Python中的列表中查找环境数字

时间:2017-12-03 18:59:41

标签: python list

我无法在列表环境中查找列表中的周围数字。我们的想法是,彼此之下的列表形成一个网格。

grid= [[1, 5, 4, 1], 
       [2, 5, 3, 2], 
       [6, 3, **6**, 3], 
       [1, 4, 2, 1]]

我尝试编写的函数将给定值作为数字的位置和网格本身。该程序应找到周围的数字。例如用这个

>>> grid= [[1, 5, 4, 1], [2, 5, 3, 2], [6, 3, **6**, 3], [1, 4, 2, 1]]
>>> neighbours(2, 2, grid)
{1, 2, 3, 4, 5}

在此示例中,选择的元素是粗体6。 我不知道如何在不经常退出索引或使代码极难的情况下如何做到这一点。

任何帮助都会受到很多赞赏

4 个答案:

答案 0 :(得分:2)

收集邻居和细胞本身,然后移除细胞本身。

def neighbours(i, j, grid):
    vals = sum((row[j-(j>0):j+2] for row in grid[i-(i>0):i+2]), [])
    vals.remove(grid[i][j])
    return set(vals)

答案 1 :(得分:0)

或使用slice对象。

def neighbor(i, j, grid):
    cut_rows = slice(max(i-1, 0), i+2)
    rows = grid[cut_rows]
    cut_cols = slice(max(j-1, 0), j+2)
    throw_row = 0 if max(i-1, 0) == 0 and i != 1 else 1
    throw_col = 0 if max(j-1, 0) == 0 and j != 1 else 1
    rest = [r[cut_cols] for r in rows]
    throw_away_center = rest[throw_row].pop(throw_col)
    flat = [i for j in rest for i in j]
    return set(flat)

更新以应对0,0和1,1。 但现在看起来整个事情看起来很笨拙......

答案 2 :(得分:0)

我们需要先创建所有邻居的list,然后将其作为set返回:

def neighbours(r, c, l):
    ns = []                             #declare a neighbours list
    if r > 0:                           #check if our row is greater than 0
        ns += l[r-1][max(0, c-1):c+2]   #add to the neighbours the row - 1
    if r < len(l)-1:                    #if not the last row
        ns += l[r+1][max(0, c-1):c+2]   #add row + 1 to the neighbours
    if c > 0:                           #if column is greater than 0
        ns.append(l[r][c-1])            #add the element to the left
    if c < len(l[r])-1:                 #if column less than the right edge
        ns.append(l[r][c+1])            #add the element to the right
    return set(ns)                      #return the neighbours as a set

和一些测试表明它有效:

>>> neighbours(2, 2, grid)
{1, 2, 3, 4, 5}
>>> neighbours(0, 0, grid)
{2, 5}
>>> neighbours(3, 3, grid)
{2, 3, 6}

答案 3 :(得分:-1)

请尝试以下代码:

def neighbours(m, i, j, dist=1):
neighbors = []
i_min = max(0, i-dist)
i_max = i+dist+1
j_min = max(0, j-dist)
j_max = j+dist+1
for row in m[i_min:i_max]:
    neighbors.append(row[j_min:j_max])
# neighbors will hold all the neighbour elements as a list
# flatten the list to get the required outpout format
flat_list = [item for sublist in neighbors for item in sublist]
#remove duplicates from the list
flat_list = list(set(flat_list))
# remove the elemnt in question as it's not required for the output
flat_list.remove(grid[2][2])
return flat_list

这将为您提供所有邻居,m = grid,i,j = 2,2在您的情况下。 注意:此示例用于理解每个步骤,可以进行修改以获得所需的输出。

相关问题