您可以对ID列表进行排序,然后仅执行一次:
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']
如果输入列表已经按顺序排列,则可以避免
sorted(尽管危害不大:如果列表已经排序,Python的自适应mergesort为O(
n ))。



