【问题标题】:If a list1 containing some elements of list2. Does list1 also changes if list2 changes?如果一个 list1 包含 list2 的一些元素。如果 list2 发生变化, list1 也会发生变化吗?
【发布时间】:2021-06-27 03:42:21
【问题描述】:

这就是我想要创造的。

list2 =[1,2,3];

list1= [list2[0],list2[1]];

list2[0]=2;

print(list1);

我希望输出是 [2,2] 而不是 [1,2]

【问题讨论】:

  • 我想你的意思是 print(list1)

标签: arrays python-3.x list sudoku


【解决方案1】:

Python 中的整数是不可变的。这是您对列表所期望的行为,但这是不可能的。考虑这个例子:

x = 0
y = 0
print(id(x), id(y))
y = 1
print(id(y))

输出:

94583099374048 94583099374048
94583099374080

而列表是mutable

a_list = ["a",
                 "b",
                 "c",
                 "d",
                 "e",
                 "f"
                 ]
b_list = a_list
print("a list id before update", id(a_list))
print("b list id before update", id(b_list))

a_list += ["g"]
print("a list after update", a_list)
print("b list after update", b_list)
print("a list id after update", id(a_list))
print("b list id after update", id(b_list,))

输出:

a list id before update 139734649089472
b list id before update 139734649089472
a list after update ['a', 'b', 'c', 'd', 'e', 'f', 'g']
b list after update ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a list id after update 139734649089472
b list id after update 139734649089472

这解释了您所看到的行为。 list1list2 存储在不同的内存位置,因为您没有将列表本身等同起来。因此list1[0]list2[0] 之间没有联系。

注意:id() 返回一个对象的内存地址。

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多