Skip column
How do I scroll through each column in a 2D array?
To iterate over each column, simply swipe through the transposed matrix (the transposed matrix is ββjust a new matrix in which the rows of the original matrix are now columns and vice versa) .
Response to the proposed problem / example
I would like to make a method that checks for the presence of at least one column in a 2D array, that the column has the same values
General method:
def check(matrix): for column in zip(*matrix): if column[1:] == column[:-1]: return True return False
Single line:
arr = [[2,0,3],[4,2,3],[1,0,3]] any([x[1:] == x[:-1] for x in zip(*arr)])
Explanation:
arr = [[2,0,3],[4,2,3],[1,0,3]]
Update 01
@BenC wrote:
"You can also skip [] around the list comprehension, so that anyone simply gets a generator that can be stopped earlier if it returns a lie"
So:
arr = [[2,0,3],[4,2,3],[1,0,3]] any(x[1:] == x[:-1] for x in zip(*arr))
Update 02
You can also use sets (combined with @HelloV answer).
Single line:
arr = [[2,0,3],[4,2,3],[1,0,3]] any(len(set(x))==1 for x in zip(*arr))
General method:
def check(matrix): for column in zip(*matrix): if len(set(column)) == 1: return True return False
The set has no duplicate elements, so if you convert the list to set(x) , any duplicate element will go away, so if all elements are equal, the length of the result set is equal to one len(set(x))==1 .