问题
I have seen answers about this question but no one helped me. Some used numpy, and some people answered using other platforms that help Python to be simpler. I don't want these type of things, I want with the simple Python without importing libraries or anything more.
Let's say: I would want to do a method that checks if there's at least one column in the 2D array that the column has the same values. For example:
arr = [[2,0,3],[4,2,3],[1,0,3]]
Sending arr to my method would return True because in the third column there is in each term the number 3.
How would I write this method? How do I loop through each column in the 2D array?
回答1:
Loop through column
How do I loop through each column in the 2D array?
In order to loop through each column just loop through the transposed matrix (a transposed matrix is just a new matrix where the rows of original matrix are now columns and vice-versa).
# zip(*matrix) generates a transposed version of your matrix
for column in zip(*matrix):
do_something(column)
An answer to your proposed problem/example
I would want to do a method that checks if there's at least one column in the 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
One-liner:
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]]
# transpose the matrix
transposed = zip(*arr) # transposed = [(2, 4, 1), (0, 2, 0), (3, 3, 3)]
# x[1:] == x[:-1] is a trick.
# It checks if the subarrays {one of them by removing the first element (x[1:])
# and the other one by removing the last element (x[:-1])} are equals.
# They will be identical if all the elements are equal.
equals = [x[1:] == x[:-1] for x in transposed] # equals = [False, False, True]
# verify if at least one element of 'equals' is True
any(equals) # True
Update 01
@BenC wrote:
"You could also skip the [] around the list comprehension so that any just gets a generator that can be stopped early once/if it returns false"
so:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any(x[1:] == x[:-1] for x in zip(*arr))
Update 02
You could also use sets (merged with the answer of @HelloV).
One-liner:
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
A set does not have repeated elements, so if you transform a list into a set set(x) any duplicated element goes away, so, if all elements are equals, the lenght of resulting set is equal to one len(set(x))==1.
回答2:
A simple example, without adding the complexity of list comprehensions and the zip function is the following:
arr = [[2,0,3],[4,2,3],[1,0,2]]
def check_column_equals_index(colum):
for row in arr:
if row[colum-1] != colum:
return False
return True
print check_column_equals_index(3)
which will output True if the 3th column is equal to 3 for every row.
Nonetheless, as you might have read in some other related discussions, it might be worth considering to use Numpy or Pandas.
回答3:
1 in [len(set(i)) for i in zip(*arr)]
回答4:
Loop through a column in 2D list and no imports? How about extract columns elements to auxiliary list and then compare among themselves. You can control the process in this synoptical function:
def checkcolumn(colnum, arrex=[]):
for i in range(len(arr)):
arrex.append(arr[i][colnum])
if arrex.count(arrex[0]) == len(arrex):
return True
else:
return False
print checkcolumn(1)
Seems easiest and pretty didactic to me. Other ways of comparing elements in column can be found at: https://www.csestack.org/python-check-if-all-elements-in-list-are-same/
来源:https://stackoverflow.com/questions/34386476/how-to-loop-through-a-column-in-python