简单的arr1 = arr2和arr1 = arr2 [:]有什么区别?

时间:2016-10-26 00:01:01

标签: python list operators slice

当我使用[:]时它是值的副本而不使用它是否接受引用并更改值?

1 个答案:

答案 0 :(得分:-1)

这主要取决于被切片的对象。 经常[:]为您提供浅色副本:

a = [1, 2, 3]
b = a[:]
# `b` is distinct from `a`, but `b` references the same objects that `a` does.
print(b is a)  # False
print(all(x is y for x, y in zip(a, b))  # True

但是编写一个只返回对象本身的病理对象很容易:

class SliceMe(object):
    def __getitem__(self, obj):
        return self