Pythonは、配列内のすべての要素が同じかどうかをチェックします

このような経験があったかどうかはわかりませんが、2回の配列操作後に取得した新しい配列の各要素の値が同じかどうかを判断したいだけです。使用するnp.unique()方法は次のとおりです。コードは次のとおりです。

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
"""

出力がの場合、True配列内のすべての要素の値が同じであることを示していることがわかります。逆に、そうである場合False、配列内の要素値は異なります。

配列内の要素が複雑な場合はどうなりますか?

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
"""

ご覧のとおり、この方法は、配列要素が複雑な場合でも適用できます。ただし、小数としての配列要素が失敗する可能性がある場合、失敗とnp.round()関数を保持する必要がある有効な小数に設定すると、たとえば次のようになりprint(len(np.unique(np.round(x2 / x1))) == 1)ます。

コードワードは簡単ではありません。役に立つと思ったら、手を挙げて「いいね」を付けて、もっと多くの人に見てもらいましょう〜

おすすめ

転載: blog.csdn.net/u011699626/article/details/112256541