赞
踩
写这个专题是因为做Leetcode第88题被两个写法坑了一下
nums1 = sorted(nums1[:m]+nums2[:n])
nums1[:] = sorted(nums1[:m]+nums2[:n])
乍一看没什么区别,但实际上第一行的写法会变动原有num1的物理地址,而第二种不会变动物理地址,只是修改当前地址里的内容。详细请看下文。
常规操作,看看就行
#a[x:y] 左闭右开 a = [[1,2,3,4],\ [5,6,7,8],\ [9,10,11,12],\ [-1,-2,-3,-4]] print(a[:2]) print(a[1:]) b = [1,2,3,4,5,6,7,8,9,10] #逆序 print(b[::-1]) #间隔 print(b[::2]) print(b[::4])
output:
[[1, 2, 3, 4], [5, 6, 7, 8]]
[[5, 6, 7, 8], [9, 10, 11, 12], [-1, -2, -3, -4]]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 3, 5, 7, 9]
[1, 5, 9]
a = [1,2,3,4]
b = [9,8,7,6]
#python中没有真正的赋值 等号可以理解为绑定
#改c也会改动a
#可以看到a、c内存地址一样
c = a
c[0] = 999
print(c)
print(a)
print(id(a),id(c))
output:
[999, 2, 3, 4]
[999, 2, 3, 4]
1941272299200 1941272299200
a = [1,2,3,4]
b = [9,8,7,6]
c = [114514]
print(id(c))
#冒号语句在右边会为当前对象创建一个新地址
#改c不会变动a
c = a[:]
c[0] = 999
print(c)
print(a)
print(id(a),id(c))
output:
1941309309504
[999, 2, 3, 4]
[1, 2, 3, 4]
1941311084864 1941311555328
a = [1,2,3,4]
b = [9,8,7,6]
#冒号语句在左边会变动左边对象的内容 地址不变
c = a
print(id(a),id(c))
c[:] = b
print(c)
print(a)
print(id(a),id(c),id(b))
output:
1941271365120 1941271365120
[9, 8, 7, 6]
[9, 8, 7, 6]
1941271365120 1941271365120 1941307133568
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。