擅长:python、mysql、java
<p>您可以对ID列表进行排序,然后只单步执行一次:</p>
<pre><code>def find_gaps(ids):
"""Generate the gaps in the list of ids."""
j = 1
for id_i in sorted(ids):
while True:
id_j = '%07d' % j
j += 1
if id_j >= id_i:
break
yield id_j
>>> list(find_gaps(["0000001", "0000003", "0000006"]))
['0000002', '0000004', '0000005']
</code></pre>
<p>如果输入列表已经按顺序排列,那么您可以避免<code>sorted</code>(尽管它没有什么害处:如果列表已经排序,Python的<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt" rel="noreferrer">adaptive mergesort</a>是O(<em>n</em>)。在</p>