擅长:python、mysql、java
<p>一种方法是将<a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer">^{<cd1>}</a>与<a href="https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.windowed" rel="nofollow noreferrer">^{<cd2>}</a>结合使用:</p>
<pre><code>import itertools as it
import more_itertools as mit
l_in = [0, 1, 2, 3]
n = len(l_in)
list(it.islice(mit.windowed(it.cycle(l_in), 3), n-1, 2*n-1))
# [(3, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, 0)]
</code></pre>
<p>在这里,我们生成了一个<a href="https://stackoverflow.com/questions/8269916/what-is-sliding-window-algorithm-examples">sliding windows</a>的无限循环,并切片了所需的子集。在</p>
<hr/>
<p>FWIW,这里是后一个代码的抽象,对于给定任何iterable输入的通用、灵活的解决方案,例如<code>range(5)</code>、<code>"abcde"</code>、<code>iter([0, 1, 2, 3])</code>等:</p>
^{pr2}$
<p>注意:<a href="https://github.com/erikrose/more-itertools" rel="nofollow noreferrer">^{<cd6>}</a>是一个单独的库,可以通过以下方式轻松安装:</p>
^{3}$