使用自定义比较器设置交集?

2024-10-03 00:18:29 发布

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

我有一套绳子

set_a = {'abcd', 'efgh', 'ghij'}
set_b = {'abce', 'efgk', 'ghij'}

我想找到这两个集合的交集,但是元素相等定义如下

^{pr2}$

基本上,如果lcs至少是字符串长度的80%,我们认为这个匹配“足够”。我知道将自定义比较器传递给排序方法是这样的,但在set操作中我还没有找到任何自定义比较器的东西。在


Tags: 方法字符串元素定义排序abcdset绳子
2条回答

可以迭代两个集合的笛卡尔积,然后保留两个集合中的元素并满足谓词

from itertools import product
{i for i,j in product(set_a, set_b) if i in set_b and match(i,j)}

使用列表压缩并添加新函数:

def match_with_set(string_a, set_b, threshold=0.8):
    for string in set_b:
        if match(string_a, string, threshold):
             return True
    return False

intersection_set = set([ string for string in set_a if match_with_set(string, set_b)])

相关问题 更多 >