Day26(0210) <<
Previous Next >> Day27(0211)
list串列(三)
串列解析
串列解析提供了更簡潔有力的方式來建立串列,利用for or if來進行串列的建立,例如:
>>>list1 = [i for i in range(10) if i < 8]
>>>list1
[0,1,2,3,4,5,6,7]
del敘述
del敘述可用來從串列中刪除指定索引之元素,例如:
>>>L = [1,2,3,4,5,6,7]
>>>del L[0]
>>>L
[2,3,4,5,6,7]
此外del敘述也可用來刪除變數,例如:
>>> L = [1,2,3,4,5]
>>> del L
>>> L
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
L
NameError: name 'L' is not defined
二維串列
二維串列其實就是巢狀串列,串列中的元素也是串列,以下列成績表格為例:
|
math |
english |
Chinese |
student A |
90 |
80 |
60 |
student B |
60 |
98 |
97 |
student C |
95 |
75 |
75 |
上列成績表格寫為串列:
>>>grades = [[90,80,60],[60,98,97],[95,75,75]]
若要存取此二維串列,必須使用兩個索引,第一個索引為列索引(row index),第二個為行索引,如下列表格所示:
|
math |
english |
Chinese |
student A |
[0][0] |
[0][1] |
[0][2] |
student B |
[1][0] |
[1][1] |
[1][2] |
student C |
[2][0] |
[2][1] |
[2][2] |
利用此二索引檢驗是否正確,如下:
>>>grades = [[90,80,60],[60,98,97],[95,75,75]]
>>>grades[0]
[90,80,60]
>>>grades[0][0]
90
Day26(0210) <<
Previous Next >> Day27(0211)