Python中的Lists是mutable个序列.这意味着您可以在创建列表后修改列表的元素.
您正在创建一个列表并将其分配给变量"tempArr".然后在第一个循环中,将"tempArr"附加到"res"列表中.
您可以使用的明确示例如下:
# Create a new list
tempArr = []
# Create a list containing the initial one (which is empty)
res = [tempArr]
# Now, lets modify the 'tempArr'
tempArr.append("This wasn't here before")
# Make your prediction on what will happen now:
print(res)
我们可以做的另一件事是在代码中使用"是"比较:
arr = [1,2,3]
tempArr = []
res = []
for num in range(0,3):
tempArr.append(arr[num])
res.append(tempArr)
# Check if the element we have appended into 'res' is the 'tempArr' list. The result is always True.
print(tempArr is res[-1])
print(tempArr, res)
# Let's compare the three elements of the 'res' list and check if they are the same list, we see that they are.
print(res[0] is res[1] is res[2])
另一方面,在第二个循环中,您不是将"tempArr"列表附加到"res"中,而是首先通过调用"list(tempArr)"创建一个新列表,然后将此新列表附加到"res"中.现在我们可以玩一下这个:
tempArr = []
res = []
for num in range(0,3):
tempArr.append(arr[num])
res.append(list(tempArr))
# Check if the element we have appended into 'res' is the 'tempArr' list.
print(tempArr is res[-1])
# This time the result is False. So we are not appending 'tempArr', but a new list with the same elements.
print(tempArr, res)
# Let's compare again the three elements of the 'res' list and see if they are the same elements:
print(res[0] is res[1] is res[2])
因此,因为在第二个循环中,我们正在创建新的列表,当您修改初始列表时,这不会影响"res"列表中的元素.