天池龍珠計劃 Python訓練營
所記錄的知識點
- 清單推導式
- 清單的乘法運算
- 清單乘法與對象指針
- 混合清單
- 清單的淺拷貝
- 二維元組
- 解壓元組
1、清單推導式
利用清單推導式建立二維數組
In [1]: [[0 for col in range(3)] for row in range(5)]
Out[1]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [2]: [[row+col for col in range(3)] for row in range(5)]
Out[2]: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
2、清單的乘法運算
In [3]: [0] * 3
Out[3]: [0, 0, 0]
In [4]: [[1,2]]*3
Out[4]: [[1, 2], [1, 2], [1, 2]]
3、清單乘法與對象指針
x = [a]*4 是建立了4個指向a的引用。a變了的話,x也會随着變化
In [14]: a = [0]*3
In [15]: x = [a]*4
In [16]: x
Out[16]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [17]: x[0][0]=1
In [18]: x
Out[18]: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
In [19]: id(x[0])
Out[19]: 1242756301896
In [20]: id(x[1])
Out[20]: 1242756301896
In [21]: id(x[2])
Out[21]: 1242756301896
4、混合清單
混合了各種類型元素的清單
In [22]: x=[1,1.2,"hello",[1,2,3]]
In [23]: x
Out[23]: [1, 1.2, 'hello', [1, 2, 3]]
5、清單的淺拷貝
清單的淺拷貝的注意點
要注意 list3=list1[:] 這種拷貝方式,雖然 id(list1) != id(list3) ,但是 id(list1[0]) == id(list3[0]
In [24]: list1=[[1,2,3],[4,5,6]]
In [25]: list2=list1
In [26]: list3=list1[:]
In [27]: list1,list2,list3
Out[27]: ([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]])
In [28]: id(list1),id(list2),id(list3)
Out[28]: (1242757039816, 1242757039816, 1242756375176)
In [29]: id(list1[0]),id(list2[0]),id(list3[0])
Out[29]: (1242756314248, 1242756314248, 1242756314248)
6、二維元組
建立二位元組
In [30]: a = (1,2),(2,3,4)
In [31]: a
Out[31]: ((1, 2), (2, 3, 4))
In [32]: a[0][0]
Out[32]: 1
7、解壓元組
解壓元組 、 通配符 * (代表一個或多個元素) 、 下劃線 _
In [36]: temp = (1,2,3)
In [37]: a,b,c = temp
In [38]: a
Out[38]: 1
In [39]: b
Out[39]: 2
In [40]: c
Out[40]: 3
In [41]:
In [41]: temp = (1,2,3,4,5,6)
In [42]: a,b,*rest,end = temp
In [43]: a
Out[43]: 1
In [44]: b
Out[44]: 2
In [45]: rest
Out[45]: [3, 4, 5]
In [46]: end
Out[46]: 6
In [47]:
In [47]: a,b,*_ = temp
In [48]: a
Out[48]: 1
In [49]: b
Out[49]: 2
In [50]: _
Out[50]: [3, 4, 5, 6]
In [51]:
歡迎各位同學一起來交流學習心得!