一文了解 Python 中最實用的 30 個內置函數
Python之所以易學易用,最大的秘密就在于它提供了豐富的內置函數。如果把Python比作一個工具箱,那么這些內置函數就是最常用的30把"瑞士軍刀"。掌握它們,就能快速解決80%的編程問題。
本文用基礎案例和易懂的代碼,幫你30分鐘內掌握Python編程的基礎工具庫。

一、數據轉換函數:生活中隨處可見
想象你在超市結賬,收銀員需要把不同商品的價格轉換成統一格式。Python也是這樣——經常需要在不同數據類型間轉換。
1. int() 和 str() —— 類型轉換的兩個基本工具
# 場景:電商平臺讀取用戶輸入
quantity_str = "5" # 用戶輸入的字符串
quantity = int(quantity_str) # 轉換為整數
price_per_item = 19.9
total_price = quantity * price_per_item
print(f"購買 {quantity} 件,總價:{total_price} 元")
# 輸出:購買 5 件,總價:99.5 元把數字轉成文字:
# 把計算結果展示給用戶
total = 99.5
message = "您需要支付 " + str(total) + " 元"
print(message) # 輸出:您需要支付 99.5 元2. list() 和 tuple() —— 容器間的相互轉換
生活場景:班級名單需要在Excel表單(列表)和紙質表單(元組)間轉換。
# 從元組轉列表:增加學生
original_students = ('張三', '李四', '王五') # 期末成績(不能改)
current_students = list(original_students) # 轉為列表(可以改)
current_students.append('趙六') # 新學期加入新生
print(current_students) # 輸出:['張三', '李四', '王五', '趙六']為什么這樣做:元組是不可變的,用于保護重要數據;列表是可變的,便于日常操作。
3. dict() —— 創建"關鍵字-數值"對應表
生活場景:記錄每個學生的成績。
# 用dict()從列表對創建字典
scores_list = [('張三', 85), ('李四', 92), ('王五', 78)]
scores_dict = dict(scores_list)
print(scores_dict) # 輸出:{'張三': 85, '李四': 92, '王五': 78}
# 或者直接用關鍵字參數
person = dict(name='張三', age=25, city='北京')
print(person) # 輸出:{'name': '張三', 'age': 25, 'city': '北京'}二、序列處理函數:處理數據集合的黃金工具
如果說上面的函數是基礎,這一類函數就是真正的威力所在——它們能讓你快速處理數百萬數據。
4. len() —— 快速計算長度
生活場景:查看購物車里有多少件商品。
shopping_cart = ['蘋果', '牛奶', '面包', '雞蛋']
item_count = len(shopping_cart)
print(f"購物車里共有 {item_count} 件商品") # 輸出:購物車里共有 4 件商品5. range() —— 生成數字序列
生活場景:批量生成員工工號(從001到100)。
# 生成前5個工號
for id_num in range(1, 6):
employee_id = f"EMP{id_num:03d}" # 格式化為3位數
print(employee_id)
# 輸出:EMP001, EMP002, EMP003, EMP004, EMP005
# 每隔10生成一個月份提醒
for month in range(1, 13, 3): # 從1到12,每次+3
print(f"第 {month} 個月") # 輸出:第1、4、7、10個月6. enumerate() —— 帶上位置序號處理列表
生活場景:閱卷老師逐一檢查答題卡,需要記錄第幾份卷子有問題。
answer_sheets = ['A卷', 'B卷', 'C卷', 'D卷']
for position, sheet_type in enumerate(answer_sheets, start=1): # start=1表示從1開始計數
print(f"第 {position} 份:{sheet_type}")
# 輸出:第 1 份:A卷,第 2 份:B卷...7. zip() —— 把多個列表"拉鏈"在一起
生活場景:配對學生姓名和成績進行公示。
names = ['張三', '李四', '王五']
scores = [92, 85, 88]
for name, score in zip(names, scores):
print(f"{name}:{score}分")
# 輸出:張三:92分,李四:85分,王五:88分8. sorted() —— 排序數據
生活場景:把考試成績從高到低排列。
# 升序排列
scores = [85, 92, 78, 95, 88]
sorted_asc = sorted(scores)
print(sorted_asc) # 輸出:[78, 85, 88, 92, 95]
# 降序排列
sorted_desc = sorted(scores, reverse=True)
print(sorted_desc) # 輸出:[95, 92, 88, 85, 78]
# 復雜排序:按成績降序,相同成績按姓名升序
data = [('張三', 92), ('李四', 92), ('王五', 85)]
sorted_data = sorted(data, key=lambda x: (-x[1], x[0]))
print(sorted_data) # 張三和李四都是92分,但字典序排在后面9. map() —— 對每個元素應用相同操作
生活場景:給所有商品打九折。
original_prices = [99, 199, 299, 399]
discount_rate = 0.9
discounted = list(map(lambda price: price * discount_rate, original_prices))
print(discounted) # 輸出:[89.1, 179.1, 269.1, 359.1]
# 等價寫法(更Pythonic)
discounted_v2 = [p * 0.9 for p in original_prices]
print(discounted_v2) # 同樣的結果專家建議:對于簡單操作,列表推導式比map()更快更易讀。
10. filter() —— 篩選滿足條件的元素
生活場景:從訂單中篩選出金額超過100元的大訂單。
orders = [50, 120, 80, 250, 60, 180]
large_orders = list(filter(lambda x: x > 100, orders))
print(large_orders) # 輸出:[120, 250, 180]
# 更Pythonic的寫法
large_orders_v2 = [o for o in orders if o > 100]三、數值運算與判斷函數:計算和決策
11. sum()、max()、min() —— 統計函數
生活場景:月底總結銷售數據。
daily_sales = [1200, 1500, 1100, 1800, 1400]
total = sum(daily_sales) # 總銷售額
print(f"本周總銷售:{total}元") # 輸出:本周總銷售:7000元
best_day = max(daily_sales) # 最高銷售日
worst_day = min(daily_sales) # 最低銷售日
print(f"最好:{best_day}元,最差:{worst_day}元")
# 輸出:最好:1800元,最差:1100元12. abs() —— 取絕對值
生活場景:計算庫存偏差(不管是多了還是少了)。
expected_inventory = 500 # 預期庫存
actual_inventory = 485 # 實際庫存
deviation = abs(expected_inventory - actual_inventory)
print(f"庫存偏差:{deviation}件") # 輸出:庫存偏差:15件13. round() —— 四舍五入
生活場景:計算商品平均價格。
total_price = 199.856
quantity = 10
avg_price = total_price / quantity
rounded_price = round(avg_price, 2) # 保留2位小數
print(f"單價:{rounded_price}元") # 輸出:單價:19.99元14. all() 和 any() —— 全部條件判斷
生活場景:審核申請表,需要所有字段都填寫才能提交。
# all():所有條件都滿足才返回True
form = {
'name': '張三',
'email': 'zhangsan@example.com',
'phone': '13800138000'
}
all_filled = all(form.values()) # 檢查所有字段是否非空
print(f"表單完整:{all_filled}") # 輸出:True
# any():至少有一個條件滿足就返回True
warning_lights = [False, False, True, False] # 至少一盞燈亮著
has_warning = any(warning_lights)
print(f"系統有警告:{has_warning}") # 輸出:True四、對象與類型檢查函數:探測Python的"DNA"
15. type() —— 查看數據類型
生活場景:調試程序時判斷變量是什么類型。
data1 = 123
data2 = "123"
data3 = 123.0
print(type(data1)) # 輸出:<class 'int'>
print(type(data2)) # 輸出:<class 'str'>
print(type(data3)) # 輸出:<class 'float'>16. isinstance() —— 更智能的類型檢查
生活場景:驗證用戶輸入是否是數字類型。
def process_payment(amount):
# isinstance()能識別整數也是數字類型
if isinstance(amount, (int, float)) and amount > 0:
print(f"支付 {amount} 元成功")
else:
print("金額必須是正數")
process_payment(99.9) # 成功
process_payment("100") # 失敗17. hasattr() 和 getattr() —— 動態查詢對象屬性
生活場景:編寫通用函數處理不同類型的用戶對象。
class Employee:
name = "張三"
salary = 5000
emp = Employee()
# 檢查對象是否有某個屬性
if hasattr(emp, 'name'):
print(f"員工姓名:{emp.name}")
# 安全地獲取屬性(如果不存在用默認值)
department = getattr(emp, 'department', '未分配')
print(f"部門:{department}") # 輸出:部門:未分配18. callable() —— 檢查是否可以調用
生活場景:判斷變量是函數還是普通變量。
def greet():
return "你好"
greeting_func = greet
greeting_text = "你好"
print(callable(greeting_func)) # 輸出:True(是函數)
print(callable(greeting_text)) # 輸出:False(是字符串)五、交互與實用函數:程序與用戶的橋梁
19. print() —— 輸出到屏幕
生活場景:這是你最常用的函數。
# 基礎用法
print("Hello World")
# 多個參數自動用空格分隔
print("姓名:", "張三", "年齡:", 25)
# 輸出:姓名: 張三 年齡: 25
# 用sep改變分隔符
print("2024", "01", "15", sep="-") # 輸出:2024-01-15
# 用end改變結尾
print("第一行", end=" -> ")
print("第二行") # 輸出:第一行 -> 第二行20. input() —— 接收用戶輸入
生活場景:做一個簡單的賬戶登錄系統。
name = input("請輸入用戶名:")
password = input("請輸入密碼:")
print(f"歡迎 {name} 登錄系統")關鍵點:input()返回的總是字符串,需要時用int()轉換。
21. help() —— 查看函數幫助
生活場景:在Python交互式環境中快速查閱。
help(sorted) # 查看sorted函數的使用說明
help(dict) # 查看字典的所有方法六、三個進階但實用的函數
22. reversed() —— 反向遍歷
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
print(num, end=' ') # 輸出:5 4 3 2 123. set() —— 創建不重復的集合
生活場景:去重訪客名單。
visitors = ['張三', '李四', '張三', '王五', '李四']
unique_visitors = set(visitors)
print(unique_visitors) # 輸出:{'張三', '李四', '王五'}
print(f"共有 {len(unique_visitors)} 個不同訪客") # 輸出:共有 3 個不同訪客24. pow() —— 求冪
# 計算2的10次方
result = pow(2, 10)
print(result) # 輸出:1024
# 帶取模:計算(5^3) mod 7
result_mod = pow(5, 3, 7)
print(result_mod) # 輸出:6七、黃金實戰案例:綜合運用這30個函數
場景:電商平臺的年終銷售報告生成器
# 原始數據:[訂單號, 商品名, 單價, 數量, 日期]
orders = [
(1001, '蘋果', 9.9, 5, '2024-01-15'),
(1002, '牛奶', 19.9, 2, '2024-01-16'),
(1003, '面包', 8.5, 3, '2024-01-15'),
(1004, '雞蛋', 12.0, 10, '2024-01-17'),
(1005, '蘋果', 9.9, 2, '2024-01-17'),
]
# 1. 計算每單總額并排序
order_totals = [(
order[0],
order[1],
round(order[2] * order[3], 2) # 用round計算總額
) for order in orders]
# 2. 按總額降序排列
sorted_orders = sorted(order_totals, key=lambda x: -x[2])
# 3. 篩選出金額超過100的大訂單
large_orders = list(filter(lambda x: x[2] > 50, sorted_orders))
# 4. 統計關鍵數據
total_revenue = sum(order[2] for order in order_totals)
max_order = max(order_totals, key=lambda x: x[2])
min_order = min(order_totals, key=lambda x: x[2])
avg_order = round(total_revenue / len(order_totals), 2)
# 5. 輸出報告
print("=" * 50)
print("年終銷售報告")
print("=" * 50)
print(f"總銷售額:{total_revenue}元")
print(f"平均訂單額:{avg_order}元")
print(f"最大訂單:{max_order[1]} - {max_order[2]}元")
print(f"最小訂單:{min_order[1]} - {min_order[2]}元")
print(f"\n大訂單清單(>50元):")
for i, order in enumerate(large_orders, start=1):
print(f" {i}. 訂單{order[0]}:{order[1]} - {order[2]}元")輸出結果:
==================================================
年終銷售報告
==================================================
總銷售額:182.5元
平均訂單額:36.5元
最大訂單:雞蛋 - 120.0元
最小訂單:面包 - 25.5元
大訂單清單(>50元):
1. 訂單1004:雞蛋 - 120.0元
2. 訂單1001:蘋果 - 49.5元八、快速速查表
函數 | 功能 | 常見場景 |
int(), str(), float() | 類型轉換 | 用戶輸入處理 |
len(), range() | 長度和序列 | 循環計數 |
enumerate(), zip() | 配對處理 | 并行遍歷 |
sorted(), reversed() | 排序 | 成績排名 |
map(), filter() | 批量處理 | 數據轉換 |
sum(), max(), min() | 統計 | 財務數據 |
all(), any() | 條件檢查 | 驗證輸入 |
type(), isinstance() | 類型檢查 | 調試程序 |
print(), input() | 交互 | 用戶通信 |
九、進階建議
- 第一周:掌握前10個函數,能處理80%的日常任務。
- 第二周:學會14-18號函數,編寫更健壯的代碼。
- 第三周:融會貫通所有函數,做小項目練習。
建議:
- 不要死記硬背,在實際項目中使用
- 善用Python交互環境help()查閱
- 列表推導式通常比map()+filter()更優雅
- 優先用內置函數,它們是C語言實現的,速度快
十、總結
這30個內置函數從處理數據的len()和sorted(),到交互的input()和print(),它們串聯起了Python編程的整個生態。
掌握它們,就像學會了英語的26個字母——有了這個基礎,你就能寫出許多你想要的程序。



































