Python zip_longest 的五组边界实验:补齐、哨兵与共享引用
下面五个程序均可单独保存运行,只使用标准库与有限内存数据,不读写文件、不访问网络。每段后面列出完整标准输出;检查失败会报错,不需要借助交互式解释器。

一、先问清楚:缺一项时,是补齐还是停止?
把设备编号和读数按位置配对时,较短的一列不一定代表任务结束:也许只是末尾还没有数据。zip_longest 适合把这类缺口显式留下,但它不按设备编号查找、不排序,也不会知道两条记录在业务上是否对应。如果中间漏了一条记录,后续项仍按位置配对;这种问题需要先按键对齐,不能靠补尾部解决。
对于彼此不共享消耗状态、正常结束的有限输入,输出行数等于最长输入的项数,每行的列数等于输入个数。没有输入或者输入全部为空,就没有输出,不能凭空得到一行填充值。只有一列时,得到的仍是一元组。下面用短小数据核验这些边界,L07 还展示了三列并不等长时的结果。
如果要求所有列必须一样长,应考虑 zip 的 strict=True;如果只要共有的前缀,可用普通 zip。zip_longest 的职责是补缺,不是检查数据齐全。填充值通过 fillvalue 关键字传入,默认是 None。以上选择来自接口的不同约定,而不是哪一个函数普遍更安全。
依据:zip_longest 官方说明;zip 的长度策略。
程序1(独立运行)
from itertools import zip_longest
def check(name, actual, expected):
if actual != expected:
raise RuntimeError(f'{name}: {actual!r} != {expected!r}')
print(f'{name}: {actual!r}')
check('L01 no-inputs', list(zip_longest()), [])
check('L02 one-empty', list(zip_longest([])), [])
check('L03 all-empty', list(zip_longest([], ())), [])
check('L04 empty-left', list(zip_longest([], [10, 20], fillvalue='?')),
[('?', 10), ('?', 20)])
check('L05 empty-right', list(zip_longest('AB', [], fillvalue='?')),
[('A', '?'), ('B', '?')])
check('L06 equal', list(zip_longest('AB', [10, 20])),
[('A', 10), ('B', 20)])
check('L07 three-inputs', list(zip_longest('ABC', [10], [True, False])),
[('A', 10, True), ('B', None, False), ('C', None, None)])
check('L08 one-input', list(zip_longest('AB')), [('A',), ('B',)])
预期输出(含末尾换行)
L01 no-inputs: []
L02 one-empty: []
L03 all-empty: []
L04 empty-left: [('?', 10), ('?', 20)]
L05 empty-right: [('A', '?'), ('B', '?')]
L06 equal: [('A', 10), ('B', 20)]
L07 three-inputs: [('A', 10, True), ('B', None, False), ('C', None, None)]
L08 one-input: [('A',), ('B',)]
二、真实的 None,不能与缺口混在一起
程序二中,第一行左列的 None 来自输入,第二行左列的 None 才是补出来的。只看这两个值本身,无法恢复其来源。如果业务数据允许 None,就在这次处理开始时创建一个专用 object,作为缺失哨兵,并约定输入不能含有这个对象本身。这个约定是可靠区分的前提;若故意把同一个哨兵塞进真实输入,身份检查也无法区分它与补位。
判断缺口使用 is 或 is not,询问的是是否同一个对象;不要用等号模拟身份判断,也不要用真假值筛选缺口。N04 保留了 None、零、False 和空字符串四种真实数据,输出类型名称是为了让零与 False 的区别也看得见。N05 说明普通字符串 MISSING 并不会因为名字像标记就变成缺失。
比较业务值时,仍应使用适合业务含义的相等判断。is 不是更严格的通用等号。这里给检查函数传入的,是已经完成身份判断后的布尔值,或不含哨兵的展示结果;并没有让列表相等比较替我们识别哨兵。
依据:对象身份比较。
程序2(独立运行)
from itertools import zip_longest
def check(name, actual, expected):
if actual != expected:
raise RuntimeError(f'{name}: {actual!r} != {expected!r}')
print(f'{name}: {actual!r}')
check('N01 default-None', list(zip_longest([None], [10, 20])),
[(None, 10), (None, 20)])
missing = object()
rows = list(zip_longest([None], [10, 20], fillvalue=missing))
check('N02 real-None', (rows[0][0] is None, rows[0][0] is missing),
(True, False))
check('N03 gap-identity', rows[1][0] is missing, True)
values = [None, 0, False, '']
rows = list(zip_longest(values, range(5), fillvalue=missing))
check('N04 falsy-data', [(type(a).__name__, b) for a, b in rows
if a is not missing],
[('NoneType', 0), ('int', 1), ('bool', 2), ('str', 3)])
rows = list(zip_longest(['MISSING'], [10, 20], fillvalue=missing))
check('N05 marker-text', [a is missing for a, _ in rows], [False, True])
ordinary = object()
rows = list(zip_longest([ordinary], [10, 20], fillvalue=missing))
check('N06 other-object', (rows[0][0] is ordinary, rows[0][0] is missing),
(True, False))
预期输出(含末尾换行)
N01 default-None: [(None, 10), (None, 20)]
N02 real-None: (True, False)
N03 gap-identity: True
N04 falsy-data: [('NoneType', 0), ('int', 1), ('bool', 2), ('str', 3)]
N05 marker-text: [False, True]
N06 other-object: (True, False)
三、生成器会被推进,不会自动复制
程序三使用两个分别创建的有限生成器,记录每次产出和正常结束。构造配对迭代器以后,日志还是空的;第一次 next 才得到首行。这里观察的是生成器体尚未执行,不应推导出任何自定义可迭代对象的初始化都没有副作用。后续转为列表会继续消费剩余数据,短列结束后,长列仍会被读完。
本节消费日志与顺序是所测两个 CPython 版本和这些输入的实际观察,不是对任意迭代器实现的通用保证。日志中的 done 记录了实际到达生成器尾部。遍历完毕以后,再读取原生成器没有剩余值,再遍历同一个配对迭代器也不会重放历史。要保留小规模结果,可明确存成列表;要重新读取外部数据,则应由调用方决定怎样重新建立数据源。
最后一项特意把同一个迭代器传了两次:两列轮流从共同位置取值,而不是各自从头读一遍。因此结果是相邻元素成组,不能再套用独立输入的长度推导。本文不把这种共享消费当成复制数据的方法,也没有测量并发迭代。
依据:zip_longest 官方说明。
程序3(独立运行)
from itertools import zip_longest
def check(name, actual, expected):
if actual != expected:
raise RuntimeError(f'{name}: {actual!r} != {expected!r}')
print(f'{name}: {actual!r}')
def tracked(name, values, events):
for value in values:
events.append(f'{name}:{value}')
yield value
events.append(f'{name}:done')
events = []
left = tracked('L', ['A'], events)
right = tracked('R', [10, 20, 30], events)
pairs = zip_longest(left, right, fillvalue='?')
check('C01 before-next', events, [])
check('C02 first-row', next(pairs), ('A', 10))
check('C03 first-trace', events, ['L:A', 'R:10'])
rest = list(pairs)
check('C04 remaining', (rest, events),
([('?', 20), ('?', 30)],
['L:A', 'R:10', 'L:done', 'R:20', 'R:30', 'R:done']))
end = object()
check('C05 exhausted', (next(left, end) is end,
next(right, end) is end, list(pairs)),
(True, True, []))
shared = iter('ABC')
check('C06 shared-iterator', list(zip_longest(shared, shared, fillvalue='?')),
[('A', 'B'), ('C', '?')])
预期输出(含末尾换行)
C01 before-next: []
C02 first-row: ('A', 10)
C03 first-trace: ['L:A', 'R:10']
C04 remaining: ([('?', 20), ('?', 30)], ['L:A', 'R:10', 'L:done', 'R:20', 'R:30', 'R:done'])
C05 exhausted: (True, True, [])
C06 shared-iterator: [('A', 'B'), ('C', '?')]
四、可变 fillvalue 是同一引用,不是模板工厂
程序四把空列表作为填充值。两个缺口引用同一个 pad,改动其中一处,另一处看到的内容也随之变化。元组只是装着引用,并不会冻结里面的列表。与此同时,真实数据中的空列表与 pad 起初内容相等,却不是同一个对象;M02 专门把相等与身份分开检查。
如果每个缺口都需要一个独立的可变容器,先用专用哨兵补齐,再在发现缺口的位置调用 list() 创建新列表。M04 与 M05 验证新缺口互不共用,同时保留已有真实数据的对象。这里没有深拷贝整份输入:如果真实数据自身存在共享引用,这段转换也不会替你解除共享。
程序4(独立运行)
from itertools import zip_longest
def check(name, actual, expected):
if actual != expected:
raise RuntimeError(f'{name}: {actual!r} != {expected!r}')
print(f'{name}: {actual!r}')
pad = []
real = []
rows = list(zip_longest([real], [10, 20, 30], fillvalue=pad))
check('M01 shared-fill', (rows[1][0] is pad, rows[2][0] is pad),
(True, True))
check('M02 equal-not-identical', (real == pad, real is pad), (True, False))
rows[1][0].append('gap')
check('M03 mutation', rows, [([], 10), (['gap'], 20), (['gap'], 30)])
missing = object()
raw = zip_longest([real], [10, 20, 30], fillvalue=missing)
separate = [(list() if a is missing else a, b) for a, b in raw]
check('M04 fresh-gaps', (separate[1][0] is separate[2][0],
separate[0][0] is real), (False, True))
separate[1][0].append('only-one')
check('M05 separate-mutation', separate,
[([], 10), (['only-one'], 20), ([], 30)])
预期输出(含末尾换行)
M01 shared-fill: (True, True) M02 equal-not-identical: (True, False) M03 mutation: [([], 10), (['gap'], 20), (['gap'], 30)] M04 fresh-gaps: (False, True) M05 separate-mutation: [([], 10), (['only-one'], 20), ([], 30)]
五、报错不等于耗尽,限量也不等于超时
程序五检查两个接口错误:整数不是可迭代输入,strict 也不是 zip_longest 支持的参数。生成器正常耗尽会触发补齐,读取过程中出现的 ValueError 则继续向外传播,不会被伪装成缺失值。例子只捕获预期异常类型,不用一个宽泛的异常分支把其他故障都吞掉。
在本次两个 CPython 版本中,第二行尚未成功形成时,左侧的数字二已经被取走,右侧才报错,所以左侧剩下三。这说明失败的一行不能视为事务回滚。例子随后不再尝试恢复出错的配对迭代器;实际处理文件或远程数据时,更应自行设计重试、去重与资源清理。
只要某个输入可能无限,完整消费 zip_longest 就可能永远不结束;需要在外层限制读取次数,不能直接把它整个转为列表。E05 用有限生成器演示 islice 的两行上限,并检查未消费的尾部。这个上限限制产出数量,不保证单次 next 能及时返回,更不是网络超时控制。本文没有运行无限输入。
最后的负对照故意把两行结果写成期望一行,只在这一次检查外围捕获 RuntimeError。它证明错误预期确实能被检测出来;其余检查失败都会让程序退出。所有检查使用显式条件与 RuntimeError,而非可能在优化模式中移除的 assert。
依据:zip_longest 官方说明;islice 官方说明;assert 与优化模式。
程序5(独立运行)
from itertools import islice, zip_longest
def check(name, actual, expected):
if actual != expected:
raise RuntimeError(f'{name}: {actual!r} != {expected!r}')
print(f'{name}: {actual!r}')
def must_raise(expected, action):
try:
action()
except expected as exc:
return type(exc).__name__
raise RuntimeError(f'expected {expected.__name__}')
check('E01 not-iterable', must_raise(TypeError, lambda: zip_longest(3)),
'TypeError')
check('E02 no-strict',
must_raise(TypeError, lambda: zip_longest([], strict=True)), 'TypeError')
def broken():
yield 10
raise ValueError('bad reading')
left = iter([1, 2, 3])
pairs = zip_longest(left, broken(), fillvalue='?')
first = next(pairs)
error = must_raise(ValueError, lambda: next(pairs))
check('E03 error-propagates', (first, error), ((1, 10), 'ValueError'))
check('E04 no-rollback', list(left), [3])
source = (n for n in range(5))
prefix = list(islice(zip_longest(source, ['A'], fillvalue='?'), 2))
check('E05 bounded-prefix', (prefix, list(source)),
([(0, 'A'), (1, '?')], [2, 3, 4]))
try:
check('wrong-expected', len(list(zip_longest([1], [10, 20]))), 1)
except RuntimeError as exc:
if str(exc) != 'wrong-expected: 2 != 1':
raise
print('E06 negative-control: caught RuntimeError')
else:
raise RuntimeError('negative control did not detect the wrong value')
预期输出(含末尾换行)
E01 not-iterable: 'TypeError' E02 no-strict: 'TypeError' E03 error-propagates: ((1, 10), 'ValueError') E04 no-rollback: [3] E05 bounded-prefix: ([(0, 'A'), (1, '?')], [2, 3, 4]) E06 negative-control: caught RuntimeError
运行范围与验证
验证记录:CPython 3.12.14 与 3.13.5,各自以普通模式和 -O 模式运行,均使用 -I -S -B。五个程序共执行二十次,包含三十项正向检查和一项负对照,共一百二十四次用例执行;全部输出逐字匹配,标准错误为空,退出码均为零。结果仅覆盖本文所列版本与输入,不是对任意自定义迭代器的兼容保证。
接口说明核对于北京时间 2026 年 10 月 23 日。官方文档用于确认语义,示例数据、检查函数及测试组合为本文原创。

