[Py 百日馬 Day 4-2] List 常見的使用方法


Posted by Laihan on 2022-02-06

List 是 Python 其中一種資料結構,中文叫做 "串列" 或 "列表",可以用來儲存有順序性的元素們且可以被改變,元素可以重複亦不限同一型別,用 [] 來當作元素的容器,元素之間用 , 隔開。

建立 List

1. 直覺用法,使用 []

empty_list = []
num_list = [1, 2, 3]
mix_list = [1, "string", 3.14, True, None]
nested_list = [1, [20, 21], 3]

2. 使用內建函式 list(iterable)

iterable 是指可以迭代的東西,如:String、Tuple 等,實務上很常將字串跟 list 互轉。

print(list())          # []
print(list("str"))     # ["s", "t", "r"]

my_tuple = ("apple", "banana", "cherry")
print(list(my_tuple))   # ["apple", "banana", "cherry"]

訪問 List

list 中的元素都有個索引值,可以透過他們來訪問元素,索引值為負數代表由後往前數。
List index

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list[0])     # 1
print(my_list[-5])    # 6

nested_list = [1, [2, 3], [4, 5, 6], 7]
print(nested_list[2][1])     # 5
print(nested_list[-3][-1])   # 3

也可以給範圍取得多個元素,語法為 tmp_list[start : end],取值範圍:start <= 索引值 < end,若 start 沒輸入代表從第一個開始;end 沒輸入代表取到最後一位。

letters = ['a', 'b', 'c', 'd', 'e']
print(letters[:])       # ['a', 'b', 'c', 'd', 'e']
print(letters[1:3])     # ['b', 'c']
print(letters[:3])      # ['a', 'b', 'c']
print(letters[2:])      # ['c', 'd', 'e']
print(letters[-2:-1])   # ['d']
print(letters[-2:])     # ['d', 'e']
print(letters[:-3])     # ['a', 'b']

檢查元素是否存在

使用 in 運算子來判斷元素是否存在於 list ;使用 not in 來判斷元素是否不存在於 list。

letters = ['a', 'b', 'c', 'd', 'e']
print('c' in letters)     # True
print('c' not in letters) # False

修改 List 中的元素

一樣使用索引值來修改元素。

letters = ['a', 'b', 'c', 'd', 'e']
letters[1] = 'xxxx'                #  ['a', 'xxxx', 'c', 'd', 'e']
letters[1:4] = ['X', 'Y', 'Z']     #  ['a', 'X', 'Y', 'Z', 'e']

使用運算子操作 list

語法 敘述
a_list + b_list 將 a_list 與 b_list 串接起來
list * n list 內的元素們重複 n 次
# list 相加
num_list = [9, 8]
mix_list = ['string', (111, 222), False]
print(num_list + mix_list)    # [9, 8, 'string', (111, 222), False]

# list * n
my_list = ['i', 'Q']
print(my_list * 3)    # ['i', 'Q', 'i', 'Q', 'i', 'Q']

使用 list 物件的方法

擴增 list

方法 敘述
append(x) 把 x 加在 list 的最後面
extend(iterable) 將 iterable 接到 list 的最後面,可以一次加很多的元素
insert(idx, el) 將 el 加到 list 的指定位置,原位置的元素會順延
# append
my_list = [1, 2]
my_list.append(999)   
print(my_list)   # [1, 2, 999]

# extend
colors = ['red', 'yellow', 'blue']
another_colors = ['black', 'white']
colors.extend(another_colors)
print(colors)    # ['red', 'yellow', 'blue', 'black', 'white']

# insert
fruits = ['apple', 'banana', 'lemon']
fruits.insert(1, 'orange')  
print(fruits)    # ['apple', 'orange', 'banana', 'lemon']

刪減 list

方法 敘述
remove(x) 找到 list 中第一個 x ,並刪除它
pop([idx]) 依 index 刪除並回傳它,若沒指定就是刪除最後一個並回傳它。
clear() 刪除 list 中所有元素
# remove
colors = ['red', 'yellow', 'red', 'red', 'blue']
colors.remove('red')   # 只會刪除第一個找到的 'red'
print(colors)          # ['yellow', 'red', 'red', 'blue']

# pop(index)
colors = ['yellow', 'white', 'red', 'blue']
print(f"{colors.pop(1)} 被刪除了")  # white 被刪除了
print(colors)                      # ['yellow', 'red', 'blue']

# pop() - 不指定 index, 會刪除最後一個
print(f"{colors.pop()} 被刪除了")    # blue 被刪除了
print(colors)                       # ['yellow', 'red']

# clear
fruits = ['apple', 'banana', 'lemon']
fruits.clear()  
print(fruits)  # []

排序 list

方法 敘述
sort() 原地改變排序,若想回傳一個新的排序後的 list 或自定義排序規則可以使用內建函數 sorted()
reverse() 反轉 list 中的元素順序。
# sort
char_list = ['d', 'c', 'a', 'e', 'b']
num_list = [3, 5, 2, 1, 4]
char_list.sort()
num_list.sort()
print(char_list)   # ['a', 'b', 'c', 'd', 'e']
print(num_list)    # [1, 2, 3, 4, 5]

# reverse
char_list.reverse()
num_list.reverse()
print(char_list)   # ['e', 'd', 'c', 'b', 'a']
print(num_list)    # [5, 4, 3, 2, 1]

查索引值、出現次數

方法 敘述
index(x [, start [, end] ]) 回傳第一個 x 的 index,可以指定範圍查: start <= 索引值 < end
count(x) 回傳 x 在 list 出現的次數。
# index
colors = ['gary', 'blue', 'red', 'yellow', 'red', 'red']
print(colors.index('red'))         # 2
print(colors.index('red', 4))      # 4
print(colors.index('red', -2))     # 4
print(colors.index('red', 1, 4))   # 2

# count
print(colors.count('red'))   # 3

複製 list - copy()

回傳一個淺複製 (shallow copy) 的 list。

char_list =  ['a', 'b', 'c']
copy_list = char_list.copy()
print(copy_list)   # ['a', 'b', 'c']

刪除 list

使用關鍵字 del 來刪除 list 的索引或者 list 本身,如果直接刪除 list 本身,會造成錯誤。

char_list =  ['a', 'b', 'c', 'd', 'e', 'f']
del char_list[3]
print(char_list)   # ['a', 'b', 'c', 'e', 'f']

del char_list[1:3]
print(char_list)   # ['a', 'e', 'f']

del char_list      # NameError: name 'char_list' is not defined

參考資料


#Python







Related Posts

570. Managers with at Least 5 Direct Reports

570. Managers with at Least 5 Direct Reports

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode

如何使用 Python 設計一個簡單的計算機 入門教學

如何使用 Python 設計一個簡單的計算機 入門教學


Comments