close

Python教學時間到!還在用那麼一種串列嗎?串列可是很多變的喔!

Python教學時間到!還在用那麼一種串列嗎?串列可是很多變的喔!

 

Python教學 系列又來啦!先前的文章曾提過, 在 Python 的 List 串列【基本的List串列說明,請參考:Python控制結構6.List串列】中,我們不僅可以隨意替換、索引 List 中的物件【請參考:Python控制結構7.List串列與其他運算子的應用】,我們還可以使用「append」來增加串列中的物件。如下例所示:

 

GearList = ["BCD", "調節器", "蛙鞋"]
GearList.append("潛水面罩")
print(GearList)

 

上述範例結果為:

['BCD', '調節器', '蛙鞋', '潛水面罩']

 

我們可以使用「len」來計算 List 串列中有多少物件:

GearList = ["BCD", "調節器", "蛙鞋"]
print(len(GearList))

上述例子結果為「3」。

 

「len」可與「append」合用,Python 語法範例如下:

GearList = ["BCD", "調節器", "蛙鞋"]
GearList.append("潛水面罩")
print(len(GearList))

上述例子結果為「4」。

 

剛剛提到,在 Python 中我們可以使用「append」來增加串列中的物件。但是「append」都是把物件增加在串列的最後面。若希望物件增加到串列的中間,就用「insert」:

GearList = ["BCD", "調節器", "蛙鞋"]
index=1
GearList.insert(index,"潛水面罩")
print(GearList)

 

結果為:

['BCD', '潛水面罩', '調節器', '蛙鞋']

 

以上範例,我們在 List 串列那一行的後方,加入了「index=1」,指定索引號碼為「1」。所以,"潛水面罩"這物件就被安插在索引序號為「1」的位置。

 

Python 的 List 串列用法可說是多樣化。我們甚至可以使用「index」來查看指定物件的索引序號如下:

GearList = ["BCD", "調節器", "蛙鞋"]
index=2
GearList.insert(index,"潛水面罩")
print(GearList.index("BCD"))
print(GearList.index("蛙鞋"))
print(GearList.index("調節器"))
print(GearList.index("潛水面罩"))

 

結果為:

0
3
1
2

 

List串列尚可搭配 for 迴圈,讓 List串列中的所有物件都可以被 Python 程式執行!【請參考:Python控制結構10.for迴圈

 

相關文章 

 

arrow
arrow

    Ezra.Yii5778 發表在 痞客邦 留言(0) 人氣()