合并两个包含每个项目出现次数的列表

时间:2017-02-12 07:32:38

标签: python

所以我试图合并两个列表并让它返回一个列表,每个项目只出现一次。我得到了关于如何查看每个列表内容的引用代码:

# 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

但是我得到一个" TypeError:类型' NoneType'是不可迭代的#34;错误。而且我不确定如何解决这个问题。所以对于预期的输入和输出:

# 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]

1 个答案:

答案 0 :(得分:2)

使用内置set的Python非常简单。 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]

我将最终版本转换回列表。