【问题标题】:Why both the lists gets changed wheres only 1 tuple gets changed为什么两个列表都被更改而只有 1 个元组被更改
【发布时间】:2020-06-15 19:11:53
【问题描述】:

考虑以下涉及列表和元组的 Python 代码:

l1=[1,2,3,4]
l2=l1
l2.append(5)
print('l1:',l1)
print('l2:',l2)
t1=(1,2,3,4)
t2=t1
t2+=(5,)
print('t1:',t1)
print('t2:',t2)

当我们运行这段代码时,输​​出是:

l1:[1,2,3,4,5]
l2:[1,2,3,4,5]
t1:(1,2,3,4)
t2:(1,2,3,4,5)

为什么在列表的情况下,列表 l1 和 l2 都发生了变化,而在元组的情况下只有 1 个元组,t2 发生了变化?

【问题讨论】:

  • 如果你这样做 l2=list(l1) 它会像你期望的那样工作

标签: python python-3.x


【解决方案1】:

元组是不可变的,列表是可变的。这意味着您可以更改列表的值,但不能更改元组的值。当您执行 t2 += (5,) 时,t2 中的值被复制并与您的元组 5 连接,这将创建一个新元组,然后将其存储在 t2 中。所以 t1 和 t2 现在不指向同一个对象。您可以通过查看对象的 id 来看到这一点

l1=[1,2,3,4]
l2=l1 #this points l2 to the same list as l1
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
l2.append(5) # this changes the list that l1 and l2 points to
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
t1=(1,2,3,4)
t2=t1 # this points t2 to the same tuple as t1
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))
t2+=(5,) # This creates a new tuple and points t2 to it. t1 still points to the old tuple
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))

输出

C:\Users\cd00119621\.virtualenvs\stackoverflow-yoix_gHB\Scripts\python.exe C:\Users\cd00119621\PycharmProjects\stackoverflow\stackoverflow.py
l1: [1, 2, 3, 4] ID: 56608872
l2: [1, 2, 3, 4] ID: 56608872
l1: [1, 2, 3, 4, 5] ID: 56608872
l2: [1, 2, 3, 4, 5] ID: 56608872
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4) ID: 56771760
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4, 5) ID: 25919192

Process finished with exit code 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多