Study/Python
python에서 list 또는 numpy.array 변수의 값이 같은지 비교하는 방법
13.d_dk
2023. 8. 25. 18:48
728x90
반응형
문제의 정의
- 파이썬에서 list 또는 numpy.array 타입의 변수를 비교해야 할 때가 있음
- numpy.array의 경우 == 연산자를 통해 직접 비교를 시도하면 다음과 같은 에러를 만나기도 함
Exception has occurred: ValueError
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()...
문제 해결 방법
- list의 경우 == 연산자를 사용할 수도 있고 all과 zip의 조합 그리고 collections module을 사용할 수 있음
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# 방법 1
list1 = [1, 2, 3]
list2 = [1, 2, 3]
if list1 == list2:
print("The lists are the same.")
else:
print("The lists are different.")
# 방법 2
list1 = [1, 2, 3]
list2 = [1, 2, 3]
if all(x == y for x, y in zip(list1, list2)) and len(list1) == len(list2):
print("The lists are the same.")
else:
print("The lists are different.")
# 방법 3
from collections import Counter
list1 = [1, 2, 3, 3]
list2 = [3, 2, 3, 1]
if Counter(list1) == Counter(list2):
print("The lists are the same.")
else:
print("The lists are different.")
|
cs |
- numpy.array의 경우 아래의 numpy.array_equal()을 사용할 수 있음
1
2
3
4
5
6
|
import numpy as np
a = np.identity(4).reshape(-1)
b = np.array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])
if np.array_equal(a, b):
print("same")
|
cs |
반응형