Skip to content Skip to sidebar Skip to footer

Listing Elements In A Nested Lists Diagonally

this is my first post, i'm pretty new this awesome site. i'd like to list all elements in a 3x3 array diagonally: L = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] expected

Solution 1:

Using only Python (no NumPy):

import itertools as IT

L = [  [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9] ]
N = len(L)
d = dict()
for i,j in IT.product(range(N), repeat=2):
    d.setdefault(j-i, []).append((i,j))

print([[L[i][j] for i,j in d[k]]for k in range(-N+1, N)])    
# [[7], [4, 8], [1, 5, 9], [2, 6], [3]]

Or, even better, use Nemo's transformation (generalized to h x w shaped matrices:

L = [  [1, 2, 3,],
       [4, 5, 6,],
       [7, 8, 9,], ]

h, w = len(L), len(L[0])

print([[L[h-1-q][p-q]
        for q inrange(min(p, h-1), max(0, p-w+1)-1, -1)]
       for p inrange(h+w-1)])                             
# [[7], [4, 8], [1, 5, 9], [2, 6], [3]]

We can also put this code in a function for easier usage:

defdiagonals(L):
    """
    https://stackoverflow.com/a/31373955/190597 (unutbu)
    >>> L = array([[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]])

    >>> diagonals(L)
    [[9], [6, 10], [3, 7, 11], [0, 4, 8], [1, 5], [2]]
    """
    h, w = len(L), len(L[0])
    return [[L[h - p + q - 1][q]
             for q inrange(max(p-h+1, 0), min(p+1, w))]
            for p inrange(h + w - 1)]


defantidiagonals(L):
    """
    >>> L = array([[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8],
                   [ 9, 10, 11]])

    >>> antidiagonals(L)
    [[0], [3, 1], [6, 4, 2], [9, 7, 5], [10, 8], [11]]
    """
    h, w = len(L), len(L[0])
    return [[L[p - q][q]
             for q inrange(max(p-h+1,0), min(p+1, w))]
            for p inrange(h + w - 1)]

Post a Comment for "Listing Elements In A Nested Lists Diagonally"