Python-比较两个句子,以下哪种方法是正确的?

问题描述

我正在通过python刷新程序进行工作,遇到了以下问题,使我对如何最好地回答感到有些困惑。我已经放置了解决方案,并且已经在网上找到了一个解决方案,并且有兴趣查看社区认为哪种解决方案是最佳的,也许我的想法是错误的:

给出两个句子,构造一个数组,该数组的单词出现在一个#句子中,而不是另一个。

我的解决方案:

  A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
def findWords(A,B):
    res = []
    asplit = A.split()
    bsplit = B.split()
    #print(asplit)
    #print(bsplit)
    for item in range(len(asplit)):
        if asplit[item] not in bsplit: res.append(asplit[item])

    for item in range(len(bsplit)):
        if bsplit[item] not in asplit: res.append(bsplit[item])

    return res
        
findWords(A,B)

Internet解决方案:

A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
d={}
for w in A.split():
    if w in d:
        d[w]=d.get(w,0)+1
    else:
        d[w]=1
for w in B.split():
    if w in d:
        d[w]=d.get(w,0)+1
    else:
        d[w]=1
unmatchedW=[w for w in d if d[w]==1]
print (unmatchedW)

解决方法

这会将AB拆分为单词,这些单词存储在包含唯一单词的set()中。结果等于两个集合中元素不同的list,即集合之间的对称差异,用^运算符表示。

A = "Geeks for Geeks hello"
B = "Learning from Geeks for Geeks"

def findWords(A,B):
    return list(set(A.split(' ')) ^ set(B.split(' ')))

print(findWords(A,B))

输出:

['hello','from','Learning']

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...