擅长:python、mysql、java
<p>请注意,如果几个值相同,您的方法也不起作用,我建议您创建一个新列表,这样您就不会与可能更改的值进行比较。我建议使用<a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">^{<cd1>}</a>,这在本例中似乎非常合适:</p>
<pre><code>from itertools import groupby
res = []
for item, group in groupby([1,2,3,3,3,3,2,1]):
identicals = list(group)
# Append the item
res.append(item)
# Extend the list with x zeros where x is the number of successive duplicates
res.extend([0] * (len(identicals) - 1))
>>> res
[1, 2, 3, 0, 0, 0, 2, 1]
</code></pre>