我有一系列的字符串 - 0000001, 0000002, 0000003....高达200万.它们不是连续的.意思是有差距.在0000003之后说下一个字符串可能是0000006.我需要找出所有这些空白.在上面的例子中(0000004,0000005).
这是我到目前为止所做的 -
gaps = list()
total = len(curr_ids)
for i in range(total):
tmp_id = '%s' %(str(i).zfill(7))
if tmp_id in curr_ids:
continue
else:
gaps.append(tmp_id)
return gaps
Run Code Online (Sandbox Code Playgroud)
但正如你所猜测的那样,自从我使用以来这很慢list.如果我使用a dict,预先填充curr_ids它会更快.但填充哈希表的复杂性是多少?什么是最快的方法.
Gar*_*ees 10
您可以对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']
Run Code Online (Sandbox Code Playgroud)
如果输入列表已经按顺序排列,那么你可以避免sorted(尽管它没什么坏处:如果列表已经排序,Python的自适应合并输出是O(n)).
| 归档时间: |
|
| 查看次数: |
2258 次 |
| 最近记录: |