변수가 없음 또는 numpy.array인지 확인할 때 ValueError가 발생했습니다.
변수가 없음인지 numpy.array인지 확인하고 싶습니다.구현했습니다.check_a
이 기능을 수행합니다.
def check_a(a):
if not a:
print "please initialize a"
a = None
check_a(a)
a = np.array([1,2])
check_a(a)
그러나 이 코드는 ValueError를 발생시킵니다.앞으로 곧장 가는 길은 무엇입니까?
ValueError Traceback (most recent call last)
<ipython-input-41-0201c81c185e> in <module>()
6 check_a(a)
7 a = np.array([1,2])
----> 8 check_a(a)
<ipython-input-41-0201c81c185e> in check_a(a)
1 def check_a(a):
----> 2 if not a:
3 print "please initialize a"
4
5 a = None
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
사용.not a
여부를 테스트하기 위해a
이라None
의 다른 가능한 값을 가정합니다.a
의 진가를 발휘하다True
그러나 대부분의 NumPy 어레이는 진실한 값을 전혀 가지고 있지 않으며,not
적용할 수 없습니다.
개체가 다음과 같은지 테스트하려는 경우None
가장 일반적이고 신뢰할 수 있는 방법은 문자 그대로 사용하는 것입니다.is
와 대조하여 보다.None
:
if a is None:
...
else:
...
이는 실제 값을 가진 객체에 의존하지 않으므로 NumPy 배열과 함께 작동합니다.
참고로 테스트는 다음과 같아야 합니다.is
,것은 아니다.==
.is
개체 식별 테스트입니다. ==
인수가 무엇이든 간에 NumPy 배열은 브로드캐스트된 요소별 동일성 비교이며 부울 배열을 생성합니다.
>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
반대로 객체가 NumPy 배열인지 여부를 테스트하려면 해당 유형을 테스트할 수 있습니다.
# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
...
else:
...
사용할 수도 있습니다.isinstance
또한 돌아올 것입니다.True
해당 유형의 하위 클래스의 경우(원하는 경우).얼마나 끔찍하고 양립할 수 없는지를 고려할 때np.matrix
즉, 실제로는 이것을 원하지 않을 수 있습니다.
# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
...
else:
...
고수하기==
다른 유형을 고려하지 않고, 다음과 같은 것도 가능합니다.
type(a) == type(None)
언급URL : https://stackoverflow.com/questions/36783921/valueerror-when-checking-if-variable-is-none-or-numpy-array
'programing' 카테고리의 다른 글
Python 반복기에서 마지막 항목을 가져오는 가장 깨끗한 방법 (0) | 2023.07.18 |
---|---|
XPath를 BeautifulSoup과 함께 사용할 수 있습니까? (0) | 2023.07.18 |
루비로 표시된 개체 유형 결정 (0) | 2023.07.13 |
SQL Server, Excel "링크된 서버"에 삽입할 때 "잘못된 열 이름" 오류가 발생 (0) | 2023.07.13 |
yerr/xerr을 오차 막대가 아닌 음영 영역으로 표시 (0) | 2023.07.13 |