Вы можете использовать функцию генератора:
import re
def all_adjacent(_c, _graph):
_funcs = [lambda x,y:(x+1, y), lambda x,y:(x+1, y+1), lambda x,y:(x+1, y-1), lambda x,y:(x, y+1), lambda x,y:(x-1, y+1), lambda x,y:(x-1, y-1), lambda x,y:(x, y-1), lambda x,y:(x-1, y)]
yield _graph[_c[0]][_c[1]]
for func in _funcs:
a, b = func(*_c)
try:
if a >= 0 and b >= 0:
_val = _graph[a][b]
if _val != ' ':
yield _val
except:
pass
s = """
1 2 3
4 5 6
7 8 9
0
"""
new_data = [re.findall('\d+|\s{2,}', i) for i in filter(None, s.split('\n'))]
final_results = {c:list(all_adjacent((i, d), new_data)) for i, a in enumerate(new_data) for d, c in enumerate(a) if c != ' '}
_result = {int(a):tuple(sorted(map(int, b))) for a, b in final_results.items()}
Выход:
{1: (1, 2, 4, 5), 2: (1, 2, 3, 4, 5, 6), 3: (2, 3, 5, 6), 4: (1, 2, 4, 5, 7, 8), 5: (1, 2, 3, 4, 5, 6, 7, 8, 9), 6: (2, 3, 5, 6, 8, 9), 7: (0, 4, 5, 7, 8), 8: (0, 4, 5, 6, 7, 8, 9), 9: (0, 5, 6, 8, 9), 0: (0, 7, 8, 9)}
Редактировать: сохранение матрицы в виде списка списков:
import re
def all_adjacent(_c, _graph):
_funcs = [lambda x,y:(x+1, y), lambda x,y:(x+1, y+1), lambda x,y:(x+1, y-1), lambda x,y:(x, y+1), lambda x,y:(x-1, y+1), lambda x,y:(x-1, y-1), lambda x,y:(x, y-1), lambda x,y:(x-1, y)]
yield _graph[_c[0]][_c[1]]
for func in _funcs:
a, b = func(*_c)
try:
if a >= 0 and b >= 0:
_val = _graph[a][b]
if _val is not None:
yield _val
except:
pass
new_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [None, 0, None]]
final_results = {c:(i, d) for i, a in enumerate(new_data) for d, c in enumerate(a) if c is not None}
_result = {int(a):tuple(map(int, all_adjacent(b, new_data))) for a, b in final_results.items()}
Выход:
{1: (1, 4, 5, 2), 2: (2, 5, 6, 4, 3, 1), 3: (3, 6, 5, 2), 4: (4, 7, 8, 5, 2, 1), 5: (5, 8, 9, 7, 6, 3, 1, 4, 2), 6: (6, 9, 8, 2, 5, 3), 7: (7, 0, 8, 5, 4), 8: (8, 0, 9, 6, 4, 7, 5), 9: (9, 0, 5, 8, 6), 0: (0, 9, 7, 8)}