Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
min():最小值
語法:
min(iterable)
min(a, b, c, ...)
min(iterable, key=函數)
min(iterable, default=預設值)從一堆東西裡面,找出最小的那個。可以傳一個可迭代物件(像 list),也可以直接傳多個值:print(min([3, 1, 4, 1, 5])) # 1
print(min(10, 20, 5)) # 5
print(min("apple", "banana")) # apple(照字母排序)用 key 參數可以自訂比較的方式:
words = ["hello", "hi", "hey"]
print(min(words, key=len)) # hi(最短的字串)
nums = [3, -7, 2, -1]
print(min(nums, key=abs)) # -1(絕對值最小的)如果傳入空的可迭代物件,又沒給 default,會報錯:
# min([]) # ValueError: min() arg is an empty sequence
print(min([], default=0)) # 0(安全的做法)不同型別不能直接比大小(Python 3 不支援):
# min(1, "hello") # TypeError: '<' not supported between instances of 'str' and 'int'小小綜合例子
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 72},
{"name": "Charlie", "score": 90},
{"name": "Diana", "score": 68}
]
# 找出分數最低的學生
lowest = min(students, key=lambda s: s["score"])
print(f"最低分:{lowest['name']},{lowest['score']} 分")
# 最低分:Diana,68 分
# 找出名字最短的學生
shortest_name = min(students, key=lambda s: len(s["name"]))
print(f"名字最短:{shortest_name['name']}")
# 名字最短:Bob
# 空列表安全處理
empty_scores = []
result = min(empty_scores, default="沒有資料")
print(result) # 沒有資料


