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

    uidesignxiaoshow 發表在 痞客邦 留言(0) 人氣()