我是python的新手,在返回数组时想知道将空数组作为全局变量还是局部变量的区别。
import collections
def check_duplicates(data: list) -> list:
dupes = []
for i in data:
if data.count(i) > 1:
dupes.append(i)
return dupes
if __name__ == "__main__":
assert list(check_duplicates([1, 2, 3, 4, 5])) == [],
Your Result:[]
Right Result:[]
import collections
dupes = []
def check_duplicates(data: list) -> list:
for i in data:
if data.count(i) > 1:
dupes.append(i)
return dupes
if __name__ == "__main__":
assert list(check_duplicates([1, 2, 3, 4, 5])) == [],
Your result:[1,3,1,3]
Right result:[]
最初,我的数组在函数之外,无法返回空数组,我想知道
好吧,首先,原始代码的编写方式是正确的(但不是按照您想要的方式),一旦您为生成非空数组的列表运行它,它将停止提供空数组。唯一剩下的就是理解它为什么会这样做。
解释
首先,列表是可变的数据类型。
a = [1,2] #create a list object and bind it to the name a
b = a #both b and a are now referring to the same list object
a.append(3) #the list object a was referring to has been changed inplace, or mutated.
#notice that coincidentally b was referring to this same object
print(a) #Prints: [1,2,3]
print(b) #Prints: [1,2,3]
这意味着,如果您使用列表的方法进行更改,例如.append
,它将就地更改列表对象,并且引用它的所有名称(例如a
或b
)都将反映更改。
第二,你的原始代码,带有一些注释
dupes = [] #create an empty list, and have the name dupes refer to the list object
def check_duplicates(data: list) -> list:
for i in data:
if data.count(i) > 1:
dupes.append(i) #mutate the list object that dupes was referring to.
return dupes #return the list object dupes was referring to.
重要的是要意识到,在整个函数中,您永远不会重新分配名称dupes
,因此它会继续引用同一个列表对象。其结果是如下行为:
dupes = []
def check_duplicates(data: list) -> list:
for i in data:
if data.count(i) > 1:
dupes.append(i)
return dupes
check_duplicates([1])
print(dupes) #[]
check_duplicates([2])
print(dupes) #[]
check_duplicates([1, 1])
print(dupes) #[1, 1]
check_duplicates([2])
print(dupes) #[1, 1] !!!! The dupes list continues to refer to the object, and any further append calls just add to it
check_duplicates([99, 99, 100, 100])
print(dupes) #[1, 1, 99, 99, 100, 100]
check_duplicates([2])
print(dupes) #[1, 1, 99, 99, 100, 100]
希望这能让事情变得更清楚。dupes
名称将继续引用函数内部正在更改的列表,这就是为什么除非将dupes
重新分配给函数内部的新空列表,否则将继续获得旧结果。希望这能有所帮助。进一步阅读很好。