合并两个列表,每个项目出现一次
问题描述:
所以我试图合并两个列表并让它返回一个列表,每个项目只出现一次。我得到了关于如何看待每个列表中的内容引用代码:合并两个列表,每个项目出现一次
# 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]
答
这是非常简单的使用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]
我把最后一组转换回列表。
你还可以添加示例输入和预期输出吗? – Zero
显示输入和预期输出以获得快速帮助 – RomanPerekhrest
您是否重新发明了方向盘? 'result = list(set(list_a)| set(list_b))' –