如何获得两个字符串列表之间的差异(忽略部分匹配)

2024-06-25 23:46:37 发布

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

listA =['set', 'pet', 'get']

listB =['set_tet', 'rgrgrgrg', 'grggrr', 'get']

expected output = ['pet', 'rgrgrgrg', 'grggrr']

“set”在listB中部分存在,因此被忽略。 “pet”在listB中找不到,因此包含在内。 “get”位于listB中,因此被忽略。 不包括“set\u tet”,因为我们以前匹配了“set” 包括“rgrg”和“grggrr”,因为它与listA中的任何内容都不匹配

在Python2.7中如何做到这一点?你知道吗


Tags: 内容outputgetexpectedpetsettetlista
1条回答
网友
1楼 · 发布于 2024-06-25 23:46:37

从这个问题来看,您似乎在寻找listB + listA - intersection of listA and listB,其中对于交集,不必有完全相同的字符串,也可以是子字符串。你知道吗

您可以尝试下面的方法,我已经在python2.7.9中尝试过了

setA = set(listA)
setB = set(listB)

# union of setA and setB 
AunionB = setA | setB

# intersection of setA and setB
AinterB = setA & setB

# calculate A union B minus A intersection B
result_set = AunionB - AinterB

# convert to list
result_list = list(result_set)

# now here we have the partial search stings as well i.e.set and set_tet
# we have to omit it from final output

# create a list which will hold partial match
partial_match_candidate = []

# search for partial match in result set list
for i in range(len(result_list)-1):
    # iterate from i+1 to len(result_list)
    for j in range(i+1 , len(result_list)):
        # check if there is partial match
        if result_list[i] in result_list[j] or result_list[j] in result_list[i]:
            partial_match_candidate.append(result_list[i])
            partial_match_candidate.append(result_list[j])


# now we have to candidates to remove i.e. set and set_tet
result_list_filtered = [ val for val in result_list if val not in partial_match_candidate ]

就复杂性而言,这不是最好的,但我希望它能有所帮助。你知道吗

相关问题 更多 >