python - 在Python中初始化两个变量以指向相同的引用

标签 python pointers variables

我在这里看到了很多类似的问题,但没有一个涉及我想知道的内容。让我们举个例子。

我想从数组创建一个链接列表。忽略所有的样板文件,让我们进入这个问题的核心。

arr = [1, 2, 3, 4, 5]
tail = head = None  # this is the problematic line
for item in arr:
  tail = Node(val=item, next=None)
  tail = tail.next
return head

不用说,这是行不通的。无论 tail 指向什么,Head 始终指向 None。

我尝试过的其他一些事情:

head = tail = [] # head will point to the empty list after finishing
head = tail = any_other_singleton # does not work

我知道为什么会发生这种情况。这是因为我正在重新分配 tail 以指向节点。但我想在“head”中保留对喜欢列表的头部的引用。我怎样才能做到这一点?在其他编程语言中,这是微不足道的,但在 python 中,您必须在声明时为变量赋值,这给我带来了问题。

最佳答案

单独处理第一项即可。

arr = [1, 2, 3, 4, 5]
head = tail = Node(val=arr[0], next=None)
for item in arr[1:]:
    tail.next = Node(val=item, next=none)
    tail = tail.next
return head

关于python - 在Python中初始化两个变量以指向相同的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69122961/

相关文章:

c - 简单链表-C

php - 将在一个函数中创建的 PHP 变量传递给另一个函数

python - 在名称为连续数字的目录中循环

Python Bottle <br/> 不工作?

python - 通过艺术家更新 matplotlib 中的文本

c - 从 'void*' 到 char(*) 的非法转换?

c - 函数指针的自由数组

c - 代码有问题或者我的 IDE/comp 有问题吗?

java - 错误 "hours cannot be resolved to a variable",我做错了什么?

python - Django:根据作为另一个模型值输入的参数自动选择模型