[英]List mismatched words from two lists in Python
我想打印兩個句子中都不存在的單詞,如果一個單詞在第一個句子中出現兩次但在第二個句子中只出現一次,我也想打印那個單詞。 例如:
a = "The winter winter season is cold"
b = "The summer winter season is hot"
Output: {'winter','cold','summer','hot'}
我嘗試在 python 中使用 Set 但它給了我這個 output: {'hot', 'cold', 'summer'}
def uncommonwords(a,b):
listA = a.split()
listB = b.split()
listC = listA +listB
return set(listC) - set(listA).intersection(listB)
print(uncommonwords(a,b))
發生的事情是:
winter
在listA中只出現一次)您需要額外的單詞列表,這些單詞在a
中出現兩次,在b
中出現一次。 當您使用集合時,您會丟失句子中的單詞數。 因此,您可以使用 dict 代替:
dictA = {x:a.count(x) for x in a.split()}
dictB = {x:b.count(x) for x in b.split()}
[x for x in dictA.keys() if dictA[x]==2 and dictB[x]==1]
Output
['winter']
您可以將整個 function 壓縮成
[x for x in dictA.keys() if (x not in dictB.keys()) or (dictA[x]==2 and dictB[x]==1)] + [x for x in dictB.keys() if (x not in dictA.keys())]
Output
['winter', 'cold', 'summer', 'hot']
只需使用“集合”package
from collections import Counter
a = "The winter winter season is cold"
b = "The summer winter season is hot"
def uncommonwords(a,b):
listA = Counter(a.split())
listB = Counter(b.split())
return list((listA - listB) + (listB - listA))
print(uncommonwords(a,b))
你的 output 將是
['winter', 'cold', 'summer', 'hot']
在這種情況下,我們使用每個單詞的計數器並操縱列表和獲取結果的差異
你也可以試試這個。
a = "The winter winter season is cold"
b = "The summer winter season is hot"
def uncommonwords(a, b):
a = a.split()
b = b.split()
h = set([x for x in a if a.count(x) > 1] + [x for x in b if b.count(x) > 1])
k = set(a).symmetric_difference(set(b))
return set.union(k, h)
print(uncommonwords(a, b))
或者如果你有iteration_utilities
實用程序而不是set([x for x in a if a.count(x) > 1] + [x for x in b if b.count(x)
你可以做set(list(duplicates(a)) + list(duplicates(b)))
太
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.