在一系列的字符串中寻找间隙

2024-04-16 21:10:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的字符串-0000001, 0000002, 0000003....高达200万。它们不是相邻的。意味着有差距。在0000003之后,下一个字符串可能是0000006。我需要找出所有这些差距。在上述情况下(000000400005)。在

这就是我目前所做的-

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

但正如您所猜到的,由于我使用list,这是很慢的。如果我使用一个dict,来预填充curr\'ids会更快。但是填充哈希表的复杂性是什么呢?最快的方法是什么。在


Tags: 字符串inididsforlenrangetmp
3条回答

您可以对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的adaptive mergesort是O(n)。在

对于存储200万整数的序列,可以使用bitarray。这里的每一位表示一个整数(位数组中该索引的整数)。示例代码:

gaps = []
# bitarray is 0 based
a = bitarray.bitarray(total + 1)
a.setall(False)
for sid in curr_ids:
    a[int(sid)] = True
for i in range(1, total):
    if not a[i]:
        gaps.append('%07d' %(i))
return gaps
seq = *the sequence of strings*
n = 2000000

gaps = set(str(i).zfill(7) for i in range(1,n+1)) - set(seq)

相关问题 更多 >