声明一个空列表

Ber*_*tek 2 python

我刚注意到将两个空列表声明为:

list1 = list2 = []
Run Code Online (Sandbox Code Playgroud)

与以下相比产生了完全不同的结果:

list1 = []
list2 = []
Run Code Online (Sandbox Code Playgroud)

我不是这个问题与整个程序有关,或者结果很重要.不过这是整个计划.两种宣言方式之间有什么区别吗?

Gar*_*Jax 9

list1 = list2 = []
Run Code Online (Sandbox Code Playgroud)

将相同的空列表实例([])分配给list1和list2.这是因为对象实例是通过引用分配的.

你可以这样做:

list1, list2 = [], []
Run Code Online (Sandbox Code Playgroud)

分配两个不同的列表两个两个变量.

您可以按如下方式检查:

list1 = list2 = []
print id(list1)  # Same as id(list2)
print id(list2)  # Same as id(list1)

list1, list2 = [], []
print id(list1)  # Different than id(list2)
print id(list2)  # Different than id(list1)
Run Code Online (Sandbox Code Playgroud)


Chr*_*rle 6

list1 = list2 = []
Run Code Online (Sandbox Code Playgroud)

可以写成:

list2 = []
list1 = list2
Run Code Online (Sandbox Code Playgroud)

你所做的只是制作一个别名(有效).

  • 在python中,所有变量都只是引用.实际上我关于"别名"的陈述略有不正确.因为如果你将`2`分配给`b`,`a`仍然指向'1`.如果你能以某种方式修改`1`对象虽然(你不能),他们都会受到影响. (2认同)