所以我尝试合并两个列表,让它返回一个列表,每个列表中只出现一个条目。我得到了如何查看每个列表内容的参考代码:
# 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:argument of type'NoneType'is not iterable”错误。我不知道该怎么处理。因此,对于预期的输入和输出:
# 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]
使用Python的内置
set
非常简单。set
对象只保留唯一的值。这是我的电话:我把最后一盘换成了一张单子。你知道吗
相关问题 更多 >
编程相关推荐