gpt4 book ai didi

python - itertools islice 方法和开始参数

转载 作者:行者123 更新时间:2023-11-30 22:56:00 24 4
gpt4 key购买 nike

itertools.islice 的文档说:

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped.

用法说:

islice('ABCDEFG', 2) --> A B
islice('ABCDEFG', 2, 4) --> C D

第一个版本不应该返回 CDEFG ...跳过前两个元素 AB

最佳答案

你误读了。它有two call profiles :

itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])

如果您只传递两个参数,则第二个参数是 stop 参数,就像您传递 0 作为 start 参数一样。为了获得您期望的行为,您需要这样做:

islice('ABCDEFG', 2, None)

但要明白,对于较大的 start 值来说,这是低效的;在幕后,islice 正在迭代和丢弃,直到到达所需的start 位置,您还没有绕过迭代的工作(只是通过在CPython 中的 C 层)。

关于python - itertools islice 方法和开始参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com