萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 判斷序列是否為空:真值測試 (Truth Value Testing) 最佳實踐

核心原則

在 Python 中,**空序列 (空列表、空元組、空字典、空字串、空集合、range(0) 等) 的布林值為 `False`,非空為 `True`**。直接用 `if seq:` 或 `if not seq:` 即可,**最簡潔、最高效、最 Pythonic**。

標準用法


m1 = []
m2 = ()
m3 = {}

# 判斷非空
if m1:
    print("m1 有元素")
else:
    print("m1 為空")

# 判斷為空
if not m2:
    print("m2 為空")

# 三元運算子
status = "非空" if m3 else "空"
print(status)  # 空

為什麼不要用 `len(seq) == 0`?

寫法效能可讀性適用性
if not seq:**O(1)** 直接檢查物件旗標⭐⭐⭐⭐⭐ Python 慣用語所有內建容器、實作 `__len__`/`__bool__` 的物件
if len(seq) == 0:O(1) 但多一次函數呼叫⭐⭐⭐ 冗餘僅支援 `__len__` 不支援 `__bool__` 的舊式類別
if seq == []:O(n) 需逐元素比較 (列表)⭐ 錯誤示範**錯誤**:只能檢查列表,且建立新列表浪費記憶體

自訂類別支援真值測試


class MyContainer:
    def __init__(self, items):
        self._items = list(items)

    def __len__(self):
        return len(self._items)

    # 定義 __bool__ 明確控制真值 (Python 3)
    # Python 2 使用 __nonzero__
    def __bool__(self):
        return bool(self._items)  # 空則 False

    # 可選:支援 in 運算子
    def __contains__(self, item):
        return item in self._items

    def __iter__(self):
        return iter(self._items)

c = MyContainer([])
print(bool(c))  # False
c = MyContainer([1])
print(bool(c))  # True

特殊情況:NumPy 陣列 / Pandas Series


import numpy as np
import pandas as pd

arr = np.array([])
# ❌ ValueError: The truth value of an array with more than one element is ambiguous
# if arr: ...

# ✅ 正確方式
if arr.size == 0:       # 或 len(arr) == 0
    print("空陣列")

s = pd.Series([])
if s.empty:             # Pandas 專用屬性
    print("空 Series")

原因: NumPy/Pandas 陣列可能有多個元素,真值不明確,故拒絕隱性布林轉換,強制顯式判斷。

總結口訣

「空即是假,非空即真」—— 直接用 if seq: / if not seq:,除非是 NumPy/Pandas 物件。

copyright © 萬盛學電腦網 all rights reserved