You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia中是否有类似Python zip_longest的最长长度zip实现?

Julia 中类似 Python itertools.zip_longest 的实现方案

Julia 标准库目前没有直接对应 Python itertools.zip_longest 的内置函数,但可以通过标准库中的迭代器工具组合出等效逻辑,无需手动编写复杂的填充代码。

标准库组合实现

核心思路是对短迭代器补充指定填充值,再与长迭代器对齐后执行 zip。以填充 missing 为例:

假设我们有三个迭代器:

names = ["Alice", "Bob", "Carol", "David"]
ages = [25, 30]
scores = [85, 90, 100]
  1. 先计算最长迭代器的长度:
max_length = maximum(length.([names, ages, scores]))
  1. 对每个迭代器用填充值补全到最长长度,再执行 zip:
using Iterators  # Iterators 是 Julia 标准库组件,无需额外安装

zipped_longest = zip(
    Iterators.take(Iterators.flatten((names, Iterators.repeated(missing))), max_length),
    Iterators.take(Iterators.flatten((ages, Iterators.repeated(missing))), max_length),
    Iterators.take(Iterators.flatten((scores, Iterators.repeated(missing))), max_length)
)

执行 collect(zipped_longest) 会得到完整的对齐结果:

4-element Vector{Tuple{Union{Missing, String}, Union{Missing, Int64}, Union{Missing, Int64}}}:
 ("Alice", 25, 85)
 ("Bob", 30, 90)
 ("Carol", missing, 100)
 ("David", missing, missing)

你可以将 missing 替换为任意需要的填充值(比如 0、"" 等)。

简化封装

如果需要多次使用,可封装成通用函数:

using Iterators

function zip_longest(pad, iters...)
    max_len = maximum(length.(iters))
    padded = (Iterators.take(Iterators.flatten((itr, Iterators.repeated(pad))), max_len) for itr in iters)
    return zip(padded...)
end

调用方式示例:

collect(zip_longest(missing, names, ages, scores))

第三方包选项

如果不想自行封装,也可以使用第三方包(如 ZipLongest.jl),但这不属于标准库内置功能。

内容的提问来源于stack exchange,提问作者tdy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:35:02