Python 3.12 zip_longest 实战:用身份哨兵区分 None 与缺项
合并两列长度不同的数据时,如果较长一列的尾部不能丢掉,可以使用 itertools.zip_longest。本文按 Python 3.12 接口说明,重点解决一个常见问题:原始数据里的 None,怎样与“这一侧已经没有元素”区分开?答案是使用专用对象作为填充值,并通过身份比较识别它。

先给缺项一个独立身份
默认填充值是 None。例如左侧只有一个 None,右侧有两个元素,结果两行的左侧都会是 None。此时单看结果,无法还原哪个来自输入,哪个来自补齐。官方接口说明确认,它会持续迭代到最长输入耗尽。
先创建 MISSING = object(),再把它传给 fillvalue;判断时写 x is MISSING。不要用 if not x,否则零、空字符串和 False 也会被当成缺项;也不要用 ==,因为数据对象可以自定义相等比较。is 比较的是同一个对象。这枚哨兵应只供当前处理流程使用,不要主动把它混入真实输入。
长度边界和迭代器生命周期
对于有限输入,输出行数等于最长输入的长度,列数等于输入数量;全空输入或不传输入都没有行,单个输入得到单元素元组。它按位置配对,不排序,也不会按业务键关联。长度不等是正常情况,不会自动报错。
返回值是迭代器,读过的元素不会倒回。下面的生成器在构造配对对象时尚未产出数据,调用 next 后才前进;这种示例不代表任意自定义对象的初始化都没有副作用。遍历结束后,再次 list 同一迭代器得到空列表。迭代器协议要求耗尽后继续保持耗尽。
十二组可以直接运行的检查
将下面整段保存为 test_zip_longest.py,分别运行 python3 test_zip_longest.py 和 python3 -O test_zip_longest.py。实测环境为 CPython 3.12.14,两种模式均通过十二组检查。这里使用显式条件和抛错,不依赖会被 -O 移除的 assert 语句。输出中的字符串 <missing> 仅用于展示,实际判断始终使用对象身份。
from itertools import count, islice, zip_longest
import sys
MISSING = object()
completed = []
def require(condition, message):
if not condition:
raise AssertionError(message)
def finish(number, result):
completed.append(number)
print(f"{number:02d}: {result!r}")
def display(rows):
return [tuple("<missing>" if x is MISSING else x for x in row)
for row in rows]
def expect_error(error_type, action):
try:
action()
except error_type as error:
return type(error).__name__
raise AssertionError(f"expected {error_type.__name__}")
# 01: Default None cannot distinguish real data from padding.
rows = list(zip_longest([None], ["a", "b"]))
require(rows == [(None, "a"), (None, "b")], "default fill")
finish(1, rows)
# 02: An identity sentinel preserves None and other false values.
values = [None, 0, False, ""]
rows = list(zip_longest(values, range(5), fillvalue=MISSING))
require(rows[0][0] is None, "real None lost")
require(rows[1][0] == 0 and rows[2][0] is False, "false values lost")
require(rows[3][0] == "" and rows[4][0] is MISSING, "missing identity")
require(sum(x is MISSING for x, _ in rows) == 1, "missing count")
finish(2, display(rows))
# 03: Three unequal inputs stop at the longest, without an extra row.
rows = list(zip_longest([1, 2], ["a"], [True, False, True], fillvalue="-"))
require(rows == [(1, "a", True), (2, "-", False), ("-", "-", True)],
"unequal lengths")
finish(3, rows)
# 04: No inputs and all-empty inputs both produce no rows.
empty = [list(zip_longest()), list(zip_longest([], [], fillvalue=MISSING))]
require(empty == [[], []], "empty input")
finish(4, empty)
# 05: One input produces one-item tuples, not bare values.
rows = list(zip_longest([7, 8]))
require(rows == [(7,), (8,)], "one iterable")
finish(5, rows)
# 06: This generator is lazy; exhausted iterators do not restart.
seen = []
def source():
for value in [10, 20]:
seen.append(value)
yield value
original = source()
pairs = zip_longest(original, ["x"])
require(seen == [], "read too early")
require(next(pairs) == (10, "x") and seen == [10], "first read")
tail = list(pairs)
require(tail == [(20, None)], "remaining row")
require(list(pairs) == [] and list(original) == [], "iterator restarted")
finish(6, {"seen": seen, "tail": tail, "again": list(pairs)})
# 07: Limit output before collecting an infinite input.
numbers = count(100)
rows = list(islice(zip_longest(numbers, ["a", "b"], fillvalue=MISSING), 4))
require(display(rows) == [(100, "a"), (101, "b"),
(102, "<missing>"), (103, "<missing>")],
"bounded infinite input")
following = next(numbers)
require(following == 104, "unexpected input consumption")
finish(7, {"rows": display(rows), "next_number": following})
# 08: Every padding position reuses the same object.
pad = []
rows = list(zip_longest([], [], [1, 2], fillvalue=pad))
require(all(row[i] is pad for row in rows for i in (0, 1)), "fill identity")
rows[0][0].append(9)
require(rows == [([9], [9], 1), ([9], [9], 2)], "shared mutation")
safe = [[[] if x is MISSING else x for x in row]
for row in zip_longest([], [], [1, 2], fillvalue=MISSING)]
require(len({id(row[i]) for row in safe for i in (0, 1)}) == 4,
"fresh containers required")
finish(8, {"shared": rows, "fresh_padding_objects": 4})
# 09: Identity tests never invoke a data object's custom equality.
class EqualityTrap:
def __eq__(self, other):
raise RuntimeError("equality must not run")
value = EqualityTrap()
rows = list(zip_longest([value], [1, 2], fillvalue=MISSING))
mask = [x is MISSING for x, _ in rows]
require(mask == [False, True] and rows[0][0] is value, "identity test")
finish(9, mask)
# 10: Neither a non-iterable input nor strict= is supported.
errors = [expect_error(TypeError, lambda: zip_longest(42)),
expect_error(TypeError, lambda: zip_longest([], strict=True))]
require(errors == ["TypeError", "TypeError"], "argument errors")
finish(10, errors)
# 11: An input failure propagates instead of becoming padding.
def broken():
yield "ok"
raise RuntimeError("source failed")
pairs = zip_longest(broken(), [1, 2], fillvalue=MISSING)
require(next(pairs) == ("ok", 1), "first row before failure")
error = expect_error(RuntimeError, lambda: next(pairs))
finish(11, error)
# 12: Preserve input order and record this run's consumption order.
trace = []
def traced(label, values):
for value in values:
trace.append(f"{label}:{value}")
yield value
rows = list(zip_longest(traced("L", [3, 1, 2]), traced("R", ["c", "a"])))
require(rows == [(3, "c"), (1, "a"), (2, None)], "output order")
require(trace == ["L:3", "R:c", "L:1", "R:a", "L:2"], "read order")
finish(12, {"rows": rows, "trace": trace})
require(completed == list(range(1, 13)), "not all groups completed")
print(f"PASS {len(completed)} groups; Python {sys.version.split()[0]}; "
f"optimize={sys.flags.optimize}")从输出看三个容易踩的坑
第七组只收集四行,随后从计数器取得 104。无限输入不会因为另一侧读完就终止,因此应先用 islice 设置上限,再收集结果。若先调用 list 再切片,限制已经来不及生效。这里的四行限制只约束本次读取,没有让计数器本身变成有限序列。
第八组的四个填充位置都指向同一个列表。向其中一处追加 9,四处都会显示 [9]:fillvalue 不会为每个位置调用工厂,也不会复制对象。需要独立容器时,先用哨兵补齐,再为每个缺项创建新列表;代码验证得到四个不同对象。这不是对原始数据做深拷贝。
第九组的身份判断不会触发自定义相等方法。第十组验证非可迭代输入及 strict 参数都会产生 TypeError;第十一组验证源迭代器的 RuntimeError 原样传播,不会被伪装成缺项。第十二组保留了输入顺序,并记录本次 CPython 运行的读取顺序;不要把多路读取理解为可回滚的事务。
先决定长度不等意味着什么
如果尾部数据有业务意义,就保留并标记缺项;如果业务要求等长,应选择 zip(strict=True) 做校验。补齐只是排列数据的策略,不能替你决定缺失记录是否有效。处理外部数据时,保留 None 与缺项的区别,通常比事后猜测缺失原因更可靠。

