<p>您可以使用一个生成器来保留上一个项目并向前看一个项目:</p>
<pre><code>def gen(x):
x = iter(x)
# Get the first item and simply yield it
first = next(x)
yield first
# create a list containing the previous element, the current element and the next element
# and iterate over your input.
three = [None, first, next(x)]
for item in x:
# Update the list of elements: Remove the previous previous item and
# add the new next item.
three = three[1:] + [item]
prev, cur, nxt = three
if cur != prev and cur != nxt:
three[1] = prev # replace the current item with the previous item
yield prev
else:
yield cur
# Simply yield the last item
yield three[-1]
>>> list(gen([0, 0, 1, 0, 1, 1, 1, 0, 1, 1]))
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
</code></pre>
<p>在这种方法中,我只返回第一个和最后一个项目而不进行检查,因为只有下一个或上一个项目,而不是两个项目。如果你愿意的话,你也可以在那里放一些支票。你知道吗</p>
<p>正如@madphestics所指出的,您根本不需要这个列表,只需为<code>previous</code>、<code>current</code>和<code>next</code>项使用一个变量即可:</p>
<pre><code>def gen(x):
x = iter(x)
# Get the first item and simply yield it
first = next(x)
yield first
cur, nxt = first, next(x) # Initial current and next item
for item in x:
prev, cur, nxt = cur, nxt, item # Update the previous, current and next item
if cur != prev and cur != nxt:
cur = prev
yield prev
else:
yield cur
# Simply yield the last item
yield nxt
</code></pre>
<hr/>
<p>注意:这两种方法都会创建一个新列表,并且不会修改原始列表。你知道吗</p>