Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare the column of two 2-dim array without any third-party libraries?

Tags:

python

arrays

I can compare the rows of two 2-dim array simply by:

arr1[1] == arr2[1]

But how about columns? Is there any convenient function to do that?

like image 263
waitingkuo Avatar asked Oct 20 '25 16:10

waitingkuo


1 Answers

You'll have to iterate over the "rows" and check that all elements of the "column" are equal to the corresponding elements in the other array:

all(row_a[1] == row_b[1] for row_a, row_b in zip(arr1, arr2))

There's no such thing in pure python as "2-dim arrays", these are lists of lists.

   #    arr1         arr2
   [             [
    [1, 2, 3],     [9, 2, 8],
    [4, 5, 6],     [7, 5, 7],
    [7, 8, 9]      [3, 8, 1]
   ]             ]


   # zip(arr1, arr2)
   [
     #   row_a       row_b
     ( [1, 2, 3],  [9, 2, 8] ),
     ( [4, 5, 6],  [7, 5, 7] ),
     ( [7, 8, 9],  [3, 8, 1] )
   ]

   [
     #   row_a[1]   row_b[1]
     ( [ , 2,  ],  [ , 2,  ] ),
     ( [ , 5,  ],  [ , 5,  ] ),
     ( [ , 8,  ],  [ , 8,  ] )
   ]
  • zip documentation
  • all documentation
like image 139
Pavel Anossov Avatar answered Oct 23 '25 05:10

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!