close

不可不錯過的幾組Python的函數!還不知道的人快學起來!

不可不錯過的幾組Python的函數!還不知道的人快學起來!

Python 的 List 串列【基本的List串列說明,請參考Python教學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教學Python控制結構10.for迴圈
arrow
arrow

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