Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
list():建立列表
語法:
list() # 空列表
list(iterable) # 從可迭代物件建立列表list() 用來建立一個列表(list)。列表是 Python 最常用的資料結構之一,可以存放任意型別的元素,而且是有序、可變的。# 空列表
empty = list()
print(empty) # []
# 也可以用字面值
empty2 = []
print(empty2) # []從各種可迭代物件建立列表
# 從字串(每個字元變一個元素)
chars = list("hello")
print(chars) # ['h', 'e', 'l', 'l', 'o']
# 從 tuple
t = (1, 2, 3)
print(list(t)) # [1, 2, 3]
# 從 range
nums = list(range(5))
print(nums) # [0, 1, 2, 3, 4]
# 從 dict(取得 keys)
d = {"a": 1, "b": 2}
print(list(d)) # ['a', 'b']
# 從 set
s = {3, 1, 2}
print(list(s)) # [1, 2, 3](順序不保證)list() 與字面值 [] 的差異
建立空列表時,[] 比 list() 稍快,因為 [] 是語法層級的操作,不需要查找函數名稱。但需要將其他可迭代物件轉成列表時,就得用 list()。
# 常見用法:搭配生成器表達式
squares = list(x**2 for x in range(5))
print(squares) # [0, 1, 4, 9, 16]
# 等同於列表推導式
squares2 = [x**2 for x in range(5)]
print(squares2) # [0, 1, 4, 9, 16]list() 做淺拷貝
把一個列表傳入 list() 會得到一個新的列表(淺拷貝),修改新列表不會影響原本的。
original = [1, 2, 3]
copy = list(original)
copy.append(4)
print(original) # [1, 2, 3](不受影響)
print(copy) # [1, 2, 3, 4]注意:淺拷貝只複製第一層,巢狀的物件仍然是同一個參照。
nested = [[1, 2], [3, 4]]
copy = list(nested)
copy[0].append(99)
print(nested) # [[1, 2, 99], [3, 4]](被影響了!)小小綜合例子
# 統計成績:從逗號分隔的字串轉成數字列表
raw = "85,92,78,95,88"
scores = list(map(int, raw.split(",")))
print(scores) # [85, 92, 78, 95, 88]
# 排序(不改原列表)
sorted_scores = list(sorted(scores))
print(sorted_scores) # [78, 85, 88, 92, 95]
# 反轉
reversed_scores = list(reversed(scores))
print(reversed_scores) # [88, 95, 78, 92, 85]
# 過濾及格分數
passed = list(filter(lambda x: x >= 80, scores))
print(passed) # [85, 92, 95, 88]
# 加分 5%
boosted = list(map(lambda x: round(x * 1.05), scores))
print(boosted) # [89, 97, 82, 100, 92]