Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
max():最大值
語法:
max(iterable)
max(a, b, c, ...)
max(iterable, key=函數)
max(iterable, default=預設值)從一堆東西裡面,找出最大的那個。可以傳一個可迭代物件(像 list),也可以直接傳多個值:print(max([3, 1, 4, 1, 5])) # 5
print(max(10, 20, 5)) # 20
print(max("apple", "banana")) # banana(照字母排序)用 key 參數可以自訂比較的方式:
words = ["hello", "hi", "hey"]
print(max(words, key=len)) # hello(最長的字串)
nums = [3, -7, 2, -1]
print(max(nums, key=abs)) # -7(絕對值最大的)如果傳入空的可迭代物件,又沒給 default,會報錯:
# max([]) # ValueError: max() arg is an empty sequence
print(max([], default=0)) # 0(安全的做法)不同型別不能直接比大小(Python 3 不支援):
# max(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}
]
# 找出分數最高的學生
top = max(students, key=lambda s: s["score"])
print(f"最高分:{top['name']},{top['score']} 分")
# 最高分:Charlie,90 分
# 找出名字最長的學生
longest_name = max(students, key=lambda s: len(s["name"]))
print(f"名字最長:{longest_name['name']}")
# 名字最長:Charlie
# 搭配 min 一起用
scores = [s["score"] for s in students]
print(f"最高:{max(scores)},最低:{min(scores)},差距:{max(scores) - min(scores)}")
# 最高:90,最低:68,差距:22

