【发布时间】:2021-05-22 14:19:28
【问题描述】:
Win32 上的 Python 3.7.9(tags/v3.7.9:13c94747c7,2020 年 8 月 17 日,18:58:18)[MSC v.1900 64 位 (AMD64)]
def List_Popped(L):
L.pop(0)
return L
Li = [x for x in range(10)]
print(Li)
LiPopped = List_Popped(Li)
print(Li)
print(LiPopped)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
我无法理解为什么在 List_Poped 函数内弹出列表值会影响其外部的列表。我在 List_Poped 内外尝试了 Li.copy() ,但 Li 受到了影响。
我想在 List_Poped 中弹出列表值,结果是 LiPopped 而不影响 Li,所以我可以将原始 Li 传递给其他函数。我该怎么做?
【问题讨论】:
-
列表是可变对象。您将列表传递给您的函数,然后您的函数改变了该可变对象。
标签: python function variables scope python-3.7