将列表传递给函数时遇到问题。它似乎对list变量有全局影响,但我没有在我的函数中声明它是全局的。谁能告诉我发生了什么以及如何解决它?
def a_Minus_b(a,b):
for i in range(len(b)):
print("a= ", a)
if b[i] in a:
a.remove(b[i])
return a
x = [1,2,3,4]
a_Minus_b(x,x)
a= [1, 2, 3, 4]
a= [2, 3, 4]
a= [2, 4]
错误:
Traceback (most recent call last):
File "<pyshell#115>", line 1, in <module>
a_Minus_b(x,x)
File "<pyshell#112>", line 4, in a_Minus_b
if b[i] in a:
IndexError: list index out of range
答案 0 :(得分:0)
如果您想让您在没有副作用的情况下运作,请先复制数据。
def a_minus_b(a, b):
a = list(a) # makes a copy and assigns the copy to a new *local* variable
for val in b:
print("a = ", a)
if val in a:
a.remove(val)
return a
而不是
a = list(a)
你可以使用以下任何一种:
from copy import copy, deepcopy
a = a[:] # copies only the references in the list
a = a.copy() # copies only the references in the list
a = copy(a) # copies only the references in the list
a = deepcopy(a) # creates copies also of the items in the list
另外,你正在做的是内置在python中,它是filter
函数。
它接受一个iterable和一个函数,只返回函数求值为True
的iterable元素。
print(list(filter(a, lambda elem: elem in b))
filter
返回一个迭代器,将其转换为一个列表,在其上调用list
。