擅长:python、mysql、java
<p>您还可以使用来自<code>collections</code>模块的<code>deque</code>,并在deques上进行一次旋转,如以下示例所示:</p>
<pre><code>from collections import deque
def grouper(iterable, elements, rotations):
if elements > len(iterable):
return []
b = deque(iterable)
for _ in range(rotations):
yield list(b)[:elements]
b.rotate(1)
data = [1,2,3,4,5]
elements = 4
rotations = 5
final = list(grouper(data, elements, rotations))
print(final)
</code></pre>
<p>输出:</p>
<pre><code>[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 1], [2, 3, 4, 5]]
</code></pre>