擅长:python、mysql、java
<p>对于一般的解决方案(因为您要求成对、三元组等),请使用<a href="http://docs.python.org/3.3/library/itertools.html#itertools.tee" rel="nofollow">^{<cd1>}</a>:</p>
<pre><code>from itertools import tee
def adjacent_tuples(iterable, n=2):
iterators = tee(iterable, n)
for i, iterator in enumerate(iterators):
for j in range(i):
next(iterator)
return zip(*iterators)
</code></pre>
<p>这将使用最少的内存,并适用于任意长度的元组:</p>
<pre><code>>>> list(adjacent_tuples(range(8), 4))
[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]
</code></pre>