python 判斷是 數字 還是 list 還是 none 並考慮到 np array 情況
下面給你一個最完整、最安全、涵蓋 Python + NumPy array + None 的判斷方式。
✅ 最推薦的判斷方式(含數字 / list / None / numpy array)
import numpy as np
def type_check(x):
# None
if x is None:
return "none"
# list
if isinstance(x, list):
return "list"
# numpy array
if isinstance(x, np.ndarray):
return "ndarray"
# 單一數字(避免字串被當成 sequence)
if isinstance(x, (int, float, np.integer, np.floating)):
return "number"
return "other"
✅ 使用範例
print(type_check(None)) # none
print(type_check(3)) # number
print(type_check(3.14)) # number
print(type_check([1, 2, 3])) # list
print(type_check(np.array([1]))) # ndarray
print(type_check("abc")) # other
判斷邏輯說明
1. None
最簡單直接:
x is None
2. list
isinstance(x, list)
3. numpy array
isinstance(x, np.ndarray)
4. 單一數字
為了避免 numpy 整數 / numpy 浮點數判斷錯誤,要加入:
(int, float, np.integer, np.floating)
例如:
np.int64(5) np.float32(3.14)
都會被歸類成數字。
如果你想簡化成一行判斷
也可以用這個:
is_number = isinstance(x, (int, float, np.integer, np.floating)) is_list = isinstance(x, list) is_none = x is None is_ndarray = isinstance(x, np.ndarray)

留言板
歡迎留下建議與分享!希望一起交流!感恩!