python / python/cpython

Add clarification to zip's documentation

未關閉
#122,043 0 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs
主要語言
Python
星號
77.2k
分支
36k
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 處停止。明確說明 iterator 可能會在達到 StopIteration 之前就被消耗,並記錄所示的引數順序邊界情況,包括建議將最短的 iterator 放在最前面。完成的標準是 zip 文件中清楚說明了該行為和建議。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
documentation
Issue 類型
文件
難度
2/5
預估耗時
1-3 小時
活躍度
停滯
描述清晰度
描述清楚
新手友好度
50/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。