在Python内部如何向自身添加列表?

时间:2019-08-09 12:45:06

标签: python python-3.x

我很好奇下面这些示例的内部内容:

>>> x = []
>>> x.append(x)
>>> print(x)
[[...]]
>>> y = [1]
>>> y.append(y)
>>> print(y)
[1, [...]]
>>> len(x)
1
>>> len(y)
2
>>> x[0]
[[...]]
>>> x[0][0][0] == x
True
>>> y[0]
1
>>> y[1]
[1, [...]]

Demo link

  • 如何在内部为x创建无限嵌套的一个元素列表?

1 个答案:

答案 0 :(得分:0)

也许C中的类似示例可以帮助解释?

#include <stdio.h>

typedef struct _node {
    struct _node *next;
    int value;
} node;

int main(void) {
  node a_node;
  a_node.next = &a_node;
  a_node.value = 1;
  node *curr = &a_node;
  for (int index = 0; index < 3; index ++) {
    printf("curr = %p, curr->value = %d\n", curr, curr->value);
    curr = curr->next;
  }
  return 0;
}

输出

$ ./main
curr = 0x7fff3f26d5c8, curr->value = 1
curr = 0x7fff3f26d5c8, curr->value = 1
curr = 0x7fff3f26d5c8, curr->value = 1

您可以尝试使用repli.it。尝试将3增加到非常大的数目。

在您的repl.it中添加类似内容,以在python中获得类似内容:

z = x
for count in range(10):
  print(id(z))
  z = z[0]