504
Python的List(列表)是非常特殊的用法,像一個矩陣,裡面的項目能儲存任何資料型態,List裡也能儲存List。
#完全都是字串的列表
animal= ["dog","cat","bird"]
#完全都是數字的列表
number = [1,2,3,4]
#混合資料型態的列表
combine = [1,"harry",3+2j,[1,2,3]]
列表的用法
列表的特色是有序的能被索引單獨取出、內容可變動、同時list內不同位置的值可以重複。
索引取值
索引取列表式有序的,從左邊開始為初始位置0,像右數去,可以用索引的方式單獨取值。
nimal= ["dog","cat","bird","rabbit"]
#列表長度
print(len(animal))
#不同位置的值
print(animal[0])
print(animal[2])
print(animal[-1])
#輸出結果
>>> 4
dog
bird
rabbit
列表切割
number = [2,4,6,8,10,12]
print (number[:3])
print (number[-4:])
print (number[2:5])
#輸出結果
>>> [2, 4, 6]
[6, 8, 10, 12]
[6, 8, 10]
變更項目內容
#單一項目變更
animal= ["dog","cat","bird","rabbit"]
animal[1] = "pig"
print(animal)
#範圍變更
animal[1:3]=["ant","wolf"]
print(animal)
#輸出結果
>>> ["dog","pig","bird","rabbit"]
>>> ["dog","ant","animal","rabbit"]
結尾位置增加項目
這是最常使用的一個函式。
animal= ["dog","cat","bird","rabbit"]
#在索引位置為3的地方,插入"cow"
animal.append("sheep")
print(animal)
#輸出結果
>>> ['dog', 'cat', 'bird', 'rabbit', 'sheep']
兩個list相加擴增
animal= ["dog","cat","bird","rabbit"]
fruit = ["apple","banana"]
#再animal之後擴增fruit的list
animal.extend(fruit)
print(animal)
#輸出結果
>>> ['dog', 'cat', 'bird', 'rabbit', 'apple', 'banana']
刪去某項目
animal= ["dog","cat","bird","rabbit"]
#用項目刪去
animal.remove("rabbit")
#用索引位置刪去
animal.pop(0)
#輸出結果
>>> ['dog', 'cat', 'bird']
>>> ['cat', 'bird']
List排序
number = [2,8,6,4,12,10]
#升冪排序
number.sort()
print (number)
#降冪排序
number.sort(reverse = True)
print (number)
>>> [2, 4, 6, 8, 10, 12]
>>> [12, 10, 8, 6, 4, 2]
Python 入門學習系列文章
- PYTHON 基本語法
- PYTHON 資料型態(概念介紹篇)
- PYTHON 資料型態(數字篇)
- PYTHON 資料型態(字串篇)
- PYTHON 資料型態(LIST)
- PYTHON 資料型態(DICT)
- PYTHON 資料型態(BOOLEANS)
- PYTHON 條件判斷算式(IF,ELIF,ELSE)
- PYTHON WHILE 迴圈
- PYTHON FOR 迴圈
- PYTHON DEF 函式
- PYTHON MODULES 模組
