I don’t know if you have ever had this experience, just want to judge whether the values of each element in the new array obtained after two array operations are the same. Here is a np.unique()
method to use , the code is as follows:
import numpy as np
class Debug:
@staticmethod
def isAllElementSame():
x1 = np.array([[1, 2, 3], [3, 4, 5], [6, 7, 8]])
x2 = np.array([[81., 162., 243., ], [243., 324., 405.], [486., 567., 648.]])
print('The result if x2/x1 is:')
print(x2 / x1)
print('Judge whether all elements in array are same or not')
print(len(np.unique(x2 / x1)) == 1)
if __name__ == '__main__':
debug = Debug()
debug.isAllElementSame()
"""
The result if x2/x1 is:
[[81. 81. 81.]
[81. 81. 81.]
[81. 81. 81.]]
Judge whether all elements in array are same or not
True
"""
It can be seen that when the output is True
, it indicates that the values of all the elements in the array are the same. On the contrary, when False
it is, there are different element values in the array.
What if the elements in the array are complex?
import numpy as np
class Debug:
@staticmethod
def isAllElementSame():
x1 = np.array([complex(1, 2), complex(2, 4)])
x2 = np.array([complex(2, 4), complex(4, 8)])
print('The result if x2/x1 is:')
print(x2 / x1)
print('Judge whether all elements in array are same or not')
print(len(np.unique(x2 / x1)) == 1)
if __name__ == '__main__':
debug = Debug()
debug.isAllElementSame()
"""
The result if x2/x1 is:
[2.+0.j 2.+0.j]
Judge whether all elements in array are same or not
True
"""
As you can see, this method is still applicable when the array elements are complex. However, when the array element as a decimal may fail, if the failure plus np.round()
function and set to a valid decimal required to retain, for example: print(len(np.unique(np.round(x2 / x1))) == 1)
.
The code word is not easy, if you find it useful, please raise your hand to give a like and let me recommend it for more people to see~