LoginSignup
21
15

More than 5 years have passed since last update.

Python で配列の一致比較 (list, ndarray)

Last updated at Posted at 2018-06-21

この記事では、Python の list および numpy の ndarray において、配列を比較した際に全要素が一致しているかどうかを知る方法について記載しています。

list の場合

  • '==' や '!=' を使って比較演算した場合、全要素を見た場合の一致/不一致が返される。
  • テストコード等で配列全体の一致を調べる場合は、単純に比較演算すればよい。
ComparisonOfArray.py
test_data = [[1,2,3],[4,5,6]]
test_data1 = [[0,2,3],[4,5,6]]
actual = [[1,2,3],[4,5,6]]

print(test_data == actual)
# [out] >> True

print(test_data1 == actual)
# [out] >> False

ndarray の場合

  • '==' や '!=' を使って比較演算した場合、要素ごとの一致/不一致が返される。
  • テストコード等で配列全体の一致を調べる場合は、
    • numpy の .all() コマンドを使う。
    • python native の all() コマンドを使う。
ComparisonOfArray.py
test_data = np.array([1,2,3])
test_data1 = np.array([0,2,3])
actual = np.array([1,2,3])

# element wise comparison
print(test_data == actual)
# [out] >> [True, True, True]
print(test_data1 == actual)
# [out] >> [False, True, True]

# comparison of all the elements
# Using .all() command of the numpy
print((test_data == actual).all())
# [out] >> True
print((test_data1 == actual).all())
# [out] >> False

# Using all() command of the native python
print(all(test_data == actual))
# [out] >> True
print(all(test_data1 == actual))
# [out] >> False

Gist Link

21
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
15