python在迭代i时从集合中移除元素

2024-10-03 06:21:12 发布

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

我试图在迭代时从集合中移除元素

    matches = defaultdict(list)
    for id_a in indices:
        for id_b in indices:
            if id_a != id_b:
               if similar(id_a, id_b, threshold):
                    matches[id_a] += [id_a, id_b]
                    indices.difference_update({id_a, id_b})

def similar(a,b,threshold=0.7):
    return True if difflib.SequenceMatcher(None, a, b).ratio() > threshold else False

indices={'aaabbb', 'aabbb', 'aabb', 'aaa', 'bbb'}
matches = {‘aaabbb’: [‘aabb’, ‘aabbb’]}

indices是一个集合,similar是一个函数,它检查id_a和{}是否相似,如果列表defaultdictmatches将添加{}。在

但我有个错误:

^{pr2}$

我想知道如何解决它,同时实现目标。在


Tags: inid元素forthresholdiflistsimilar