我在网上看到一篇文章有这样的内容“对于list,切片会返回一个新的list,而不会改变原有的list“,但是下面的这段代码:
def change(x): x[1:3] = ['o', 'k'] a = [10, 20, 30]print('a is {0}'.format(a)) change(a) print('a is {0}'.format(a))
对于函数内部的这一行,x[1:3]得到的是一个新的list?如果是一个新的list应该不会对a的内容造成影响啊?为什么a会改变?
运行结果:
a is [10, 20, 30]
a is [10, 'o', 'k']
Thank you all, especially @cai870808. Thank you.
slicing和slice assignment是两个不同的概念。请参考关于这个问题的讨论:
http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice
x = [10, 20, 30] print('x is {0}'.format(x)) a = x[1:3] print('x is {0}'.format(x)) print('a is {0}'.format(a)) x[1:3] = ['o', 'k'] print('x is {0}'.format(x)) b = x[1:3] print('b is {0}'.format(b))
其实我不会Python,我猜是这样的吧
#如果你执行如下代码 >>> a = [10,20,30] >>> a[0:2] = [4,5] #该操作是赋值操作,意思是将a的前两个值赋值为4,5 >>> a [4, 5, 30] #如果你执行如下代码 >>> a = [10,20,30] >>> b = a[0:2]#这样才是切片操作,就复制了a的前两个元素 >>> b [10, 20]