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:[]
最初,我在函数之外有数组,无法返回空数组,这很奇怪
答案 0 :(得分:2)
好吧,首先,原始代码在其编写方式方面表现正确(但并没有达到您想要的方式),并且一旦为产生非空数组的列表运行它,它将停止提供空数组。剩下的唯一一件事就是了解为什么它表现得如此。
说明
首先,列表是可变的数据类型。
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
或{{1} })引用它会反映出更改。
第二,您的原始代码,带有一些注释
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
重新分配给内部的新空列表,否则您将继续获得旧结果的原因。希望这可以帮助。
Good further reading。