Pythonic way to get adjacent elements in a matrix | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pythonic way to get adjacent elements in a matrix

Given a matrix / multidimensional list, I wanted to get the adjacent elements of each element horizontally, vertically, and diagonally. My initial thought process involved creating seperate logic for elements at the edges of the matrix and another one for the ones in the middle but it seems long and unreliable. What is the most pythonic algorithm that can be implemented for this task?

16th Nov 2019, 4:47 PM
0x6176696c61
0x6176696c61 - avatar
1 Answer
0
I wouldn't say that I know for sure what would be THE most pythonic way to solve this, but I put three examples together that I would consider rather pythonic. They are plain python for the most part while using itertools product in one place. I guess there would be some good methods for this using pandas, as well, but I didn't go into that here. https://code.sololearn.com/c30LcCE11P2Y/?ref=app
16th Aug 2022, 8:25 PM
Fynn Nix
Fynn Nix - avatar