[英]List mutability with append in for loop in python
我對 for 循環上下文中列表可變性的概念不熟悉。
有人可以解釋為什么下面代碼的 output 是一個空列表嗎?
我希望L3 = [3,4]
。
謝謝!
L1 = [1,2,3,4]
L2 = [1,2,5,6]
def no_dups(L1, L2):
L3 = []
for e in L1:
if e not in L2:
L3.append(e)
return(L3)
print(L3)
最后一行print(L3)
甚至沒有調用no_dups
function。 它引發了一個期望,因為 L3 沒有在 function 之外定義。
可能你的意思是這樣的:
L3 = no_dups(L1, L2)
print(L3)
在這種情況下,您確實會得到預期的結果。
這有效:
>>> L1 = [1,2,3,4]
>>> L2 = [1,2,5,6]
>>>
>>> def no_dups(L1, L2):
... L3 = []
... for e in L1:
... if e not in L2:
... L3.append(e)
... return(L3)
...
>>> print(no_dups(L1,L2))
[3, 4]
>>>
L3
實際上並不存在於no_dups()
之外,因此您無法打印它或其他任何東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.