2017-02-12 40 views
0

所以我試圖合併兩個列表並讓它返回一個列表,每個項目只出現一次。我得到了關於如何看待每個列表中的內容引用代碼:合併兩個列表,每個項目出現一次

# contains - returns true if the specified item is in the ListBag, and 
# false otherwise. 
def contains(self, item): 
    return item in self.items 

# containsAll - does this ListBag contain all of the items in 
# otherBag? Returns false if otherBag is null or empty. 
def containsAll(self, otherBag): 
    if otherBag is None or otherBag.numItems == 0: 
     return False 
    other = otherBag.toList() 
    for i in range(len(otherBag.items)): 
     if not self.contains(otherBag.items[i]): 
      return False 
    return True 

所以我想這樣的:

def unionWith(self, other): 
    unionBag = ListBag() 

    if other is None or other.numItems == 0 and self.numItems == 0 or self is None: 
     return unionBag.items 

    for i in self.items: 
     if not unionBag.contains(self.items[i]): 
      unionBag.add(i) 
    for i in other.items: 
     if not unionBag.contains(other.items[i]): 
      unionBag.add(i) 
    return unionBag.items 

不過,我得到一個「類型錯誤:類型的參數「NoneType '不可迭代'錯誤。我不知道如何解決這個問題。所以對於預期的輸入和輸出:

# A list has been already created with the following contents: 
bag1.items 
[2, 2, 3, 5, 7, 7, 7, 8] 
bag2.items 
[2, 3, 4, 5, 5, 6, 7] 
# So the input/output would be 
bag1.unionWith(bag2) 
[2, 3, 4, 5, 6, 7, 8] 
+2

你還可以添加示例輸入和預期輸出嗎? – Zero

+0

顯示輸入和預期輸出以獲得快速幫助 – RomanPerekhrest

+0

您是否重新發明了方向盤? 'result = list(set(list_a)| set(list_b))' –

回答

2

這是非常簡單的使用Python的內置set。 A set對象只保留唯一值。這裏是我對此的呼籲:

a = [2, 2, 3, 5, 7, 7, 7, 8] 
b = [2, 3, 4, 5, 5, 6, 7] 
c = list(set(a) | set(b)) 
print(c) 

>>> 
[2, 3, 4, 5, 6, 7, 8] 

我把最後一組轉換回列表。