python / python/cpython

Add clarification to zip's documentation

未关闭
#122,043 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Documentation

Using zip on iterators of variable length results in a behavior that I believe would benefit from some additional clarification in the documentation. Take the following example:

>>> a = list(range(3))
>>> b = iter(range(100))
>>> list(zip(a, b))
[(0, 0), (1, 1), (2, 2)]
>>> list(zip(a, b))
[(0, 3), (1, 4), (2, 5)]

This is expected behavior as zip simply stops at the end of the shortest iterable, in this case a. When calling zip again a is restarted whilst b carries on from 3.

The unexpected behavior comes about when we swap the arguments putting the longer iterator as the first argument.

>>> a = list(range(3))
>>> b = iter(range(100))
>>> list(zip(b, a))
[(0, 0), (1, 1), (2, 2)]
>>> list(zip(b, a))
[(4, 0), (5, 1), (6, 2)]

Rather than carrying on from 3 like in the previous example we get a 4. I understand this is due to b being consumed during the zip and there is no way to know which iterator will yield a StopIteration first and so this is the intended behavior.

It may be beneficial to highlight this edge case in the documentation and make the recommendation to try and put the shortest iterator first.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Python 内置函数 zip 的文档开始,检查其中如何描述在最短的 iterable 处停止。明确说明迭代器可能会在达到 StopIteration 之前就被消耗,并记录所示的参数顺序边界情况,包括建议将最短的迭代器放在最前面。完成的标准是 zip 文档中清楚说明了该行为和建议。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
50/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。