<分区>
这是练习示例:
Write a function
(list1, list2)
that takes in two lists as arguments and return a list that is the result of removing elements fromlist1
that can be found inlist2
.
为什么这个函数返回 [1, 3, 4]
而不是我想的 [4]
?我认为它与 list1.remove()
有关。我想这很明显,但我看不到。
它适用于这些示例:
subtractList (['a', 'b', 'c', 'd'], ['x', 'y', 'z']) =
['a', 'b', 'c', 'd']
subtractList([1,2,3,4,5], [2, 4]) =
[1, 3, 5]
但失败了:
subtractList(range(5), range(4))
我还注意到它只从列表中删除偶数。
代码如下:
def subtractList(list1,list2):
list1 = list(list1)
list2 = list(list2)
for i in list1:
if i in list2:
list1.remove(i)
return list1
我已经解决了这个问题:
def subtractList(list1,list2):
new_list = []
list1 = list(list1)
list2 = list(list2)
for i in list1:
if i not in list2:
new_list.append(i)
return new_list