我试图理解为什么第一个for循环不返回第二个for循环返回的内容.有人能给我解释清楚吗?我的搜索没有发现任何结果,因为我不知道这个问题叫什么.

arr = [1,2,3]
tempArr = []
res = []

for num in range(0,3):
  tempArr.append(arr[num])
  res.append(tempArr)
  print(tempArr, res)

print()

tempArr = []
res = []
for num in range(0,3):
  tempArr.append(arr[num])
  res.append(list(tempArr))
  print(tempArr, res)

返回值:

[1] [[1]]
[1, 2] [[1, 2], [1, 2]]
[1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

[1] [[1]]
[1, 2] [[1], [1, 2]]
[1, 2, 3] [[1], [1, 2], [1, 2, 3]]

推荐答案

Python中的Listsmutable个序列.这意味着您可以在创建列表后修改列表的元素.

您正在创建一个列表并将其分配给变量"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"列表中的元素.

Python相关问答推荐

Pandas 密集排名具有相同值,按顺序排列

在pandas DataFrame上运行apply()时如何访问DateTime索引?

使用pandas MultiIndex进行不连续 Select

如何以实现以下所述的预期行为的方式添加两只Pandas pyramme

从Python调用GMP C函数时的分段错误和内存泄漏

使用Python Great Expectations和python-oracledb

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

如何终止带有队列的Python进程?+ 队列大小的错误?

Python 3.12中的通用[T]类方法隐式类型检索

Pandas 第二小值有条件

将jit与numpy linSpace函数一起使用时出错

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

通过Selenium从页面获取所有H2元素

如何让Flask 中的请求标签发挥作用

将9个3x3矩阵按特定顺序排列成9x9矩阵

在np数组上实现无重叠的二维滑动窗口

为一个组的每个子组绘制,

使用Python从URL下载Excel文件

启用/禁用shiny 的自动重新加载

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像