<p>如果所有短列表长度相等,您可以创建一个<code>dict</code>,其中key是<code>tuple</code>字符串,value是其中一个标签。你可以穿过<code>full_log</code>,取一个长度合适的块,看看是否可以从<code>dict</code>找到它。你知道吗</p>
<p>如果短列表的长度不同,则上述方法将不起作用,因为从<code>full_log</code>获取的块长度不是常量。在这种情况下,一种可能的解决方案是将短列表中的项添加到树结构中,其中叶节点是一个标签。然后针对<code>full_log</code>中的每个索引,查看是否可以从树中找到路径。如果找到路径,则向前跳转路径长度,否则从下一个索引开始尝试:</p>
<pre><code>from collections import defaultdict
from itertools import islice
full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
# Construct a tree
dd = lambda: defaultdict(dd)
labels = defaultdict(dd)
labels['HG89']['NS72'] = 'tc1'
labels['AB21']['BG54'] = 'tc2'
labels['KK02']['FE34'] = 'tc3'
labels['CF54']['SD62'] = 'tc4'
# Find label, return tuple (label, length) or (None, 1)
def find_label(it):
length = 0
node = labels
while node and isinstance(node, dict):
node = node.get(next(it, None))
length += 1
return node, (length if node else 1)
i = 0
result = []
while i < len(full_log):
label, length = find_label(islice(full_log, i, None))
result.append(label if label else full_log[i])
i += length
print result # ['tc2', 'tc1', 'Error', 'tc4', 'tc3']
</code></pre>
<p>上面使用的树有点像<a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow">trie</a>,但节点可以包含子节点或值(标签)。你知道吗</p>