Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有这个代码:
a = [1, 2, 3, 4, 5] a[:] = [] # and now a is also empty
语句在我阅读时a[:]创建了列表的副本a,因此如果将空列表[]分配给副本,那么为什么还要修改原始对象?
a[:]
a
[]
x = a[:]创建x一个包含与以下相同值的新列表a
x = a[:]
x
a[:] = x使现有列表a包含与x
a[:] = x
当一个表达式切换等号的两边时,它的行为会发生变化。
声明在我阅读a[:]时创建列表的副本a
除了你不是在读,你在写。切片分配的工作方式不同,因为它用序列替换切片。