快速掌握 Python 常用的 30 個內置函數
Python的強大,很大程度上源于其“開箱即用”的哲學。在這其中,內置函數(Built-in Functions)是地基中的地基,是每一位Python開發者都應爛熟于心的“母語”。它們是構建復雜邏輯的原子操作,是編寫高效、簡潔、Pythonic代碼的起點。
本文將這些最核心的30個內置函數,按照功能邏輯劃分為五大類別。我們將通過精準的定義和實用的代碼示例,助你快速構建起對Python內置函數庫的系統性認知,并將其無縫融入你的日常編程實踐中。

一、數據類型轉換:構建萬物的基石
編程的本質是數據的流動與轉換。這些函數是你塑造數據的基本工具。
1. int()
將一個字符串或數字轉換為整數。
str_num = "123"
int_val = int(str_num) # -> 123
float_num = 99.9
int_val_from_float = int(float_num) # -> 992. str()
將對象轉換為字符串。
num = 42
str_val = str(num) # -> "42"
my_list = [1, 2]
str_list = str(my_list) # -> "[1, 2]"3. float()
將一個字符串或數字轉換為浮點數。
str_num = "3.14"
float_val = float(str_num) # -> 3.14
int_num = 100
float_from_int = float(int_num) # -> 100.04. list()
將一個可迭代對象(如元組、字符串、集合)轉換為列表。
my_tuple = (1, 2, 3)
list_from_tuple = list(my_tuple) # -> [1, 2, 3]
my_string = "abc"
list_from_string = list(my_string) # -> ['a', 'b', 'c']5. tuple()
將一個可迭代對象轉換為元組。
my_list = [1, 2, 3]
tuple_from_list = tuple(my_list) # -> (1, 2, 3)6. dict()
創建字典。可以從鍵值對序列、關鍵字參數等創建。
# 從鍵值對元組列表創建
dict_from_list = dict([('a', 1), ('b', 2)]) # -> {'a': 1, 'b': 2}
# 從關鍵字參數創建
dict_from_kwargs = dict(name='Alice', age=30) # -> {'name': 'Alice', 'age': 30}7. set()
將一個可迭代對象轉換為集合,自動去除重復元素。
my_list = [1, 2, 2, 3, 1]
my_set = set(my_list) # -> {1, 2, 3}二、序列與迭代操作:Pythonic編程的核心
這些函數是處理列表、元組等序列的利器,是編寫優雅循環的關鍵。
8. len()
返回對象的長度(元素個數)。
my_list = [1, 2, 3, 4]
length = len(my_list) # -> 49. range()
生成一個整數序列,常用于for循環。
# 生成 0 到 4 的整數
for i in range(5):
print(i, end=' ') # -> 0 1 2 3 4
# 生成 2 到 7,步長為 2 的整數
for j in range(2, 8, 2):
print(j, end=' ') # -> 2 4 610. enumerate()
在迭代時,同時返回索引和值。
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit) # -> 0 apple, 1 banana, 2 cherry11. zip()
將多個可迭代對象聚合起來,并行地返回元組。
names = ['Alice', 'Bob']
ages = [30, 25]
for name, age in zip(names, ages):
print(name, age) # -> Alice 30, Bob 2512. sorted()
返回一個新的、已排序的列表,原列表不變。
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers) # -> [1, 1, 3, 4, 5, 9]
sorted_desc = sorted(numbers, reverse=True) # -> [9, 5, 4, 3, 1, 1]13. reversed()
返回一個反向的迭代器。
numbers = [1, 2, 3, 4]
for num in reversed(numbers):
print(num, end=' ') # -> 4 3 2 1```
### **14. `map()`**
將一個函數應用于可迭代對象的每個元素,返回一個迭代器。
```python
numbers = [1, 2, 3]
squared = map(lambda x: x*x, numbers)
print(list(squared)) # -> [1, 4, 9]```
### **15. `filter()`**
根據一個函數返回的布爾值,過濾可迭代對象中的元素,返回一個迭代器。
```python
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # -> [2, 4]三、數值計算與布爾判斷:邏輯的精確表達
這些函數負責處理數學運算和邏輯判斷,是算法實現的基礎。
16. abs()
返回一個數的絕對值。
val = abs(-10) # -> 1017. round()
四舍五入到指定的小數位數。
num = 3.14159
rounded_val = round(num, 2) # -> 3.1418. sum()
計算一個可迭代對象中所有元素的和。
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # -> 1519. max()
返回可迭代對象中的最大值。
numbers = [3, 1, 9, 5]
max_val = max(numbers) # -> 920. min()
返回可迭代對象中的最小值。
numbers = [3, 1, 9, 5]
min_val = min(numbers) # -> 1```
### **21. `any()`**
如果可迭代對象中至少有一個元素的布爾值為`True`,則返回`True`。
```python
bools = [False, False, True, False]
result = any(bools) # -> True22. all()
如果可迭代對象中所有元素的布爾值都為True,則返回True。
bools = [True, True, True]
result = all(bools) # -> True四、對象、類與反射:深入Python的動態內核
這些函數讓你能夠探查對象的內部,是元編程和編寫健壯代碼的關鍵。
23. type()
返回一個對象的類型。
print(type(123)) # -> <class 'int'>
print(type("hello")) # -> <class 'str'>24. isinstance()
檢查一個對象是否是指定類或其子類的實例。
class Animal: pass
class Dog(Animal): pass
my_dog = Dog()
print(isinstance(my_dog, Animal)) # -> True25. hasattr()
檢查對象是否擁有指定的屬性。
class Person:
name = 'Alice'
print(hasattr(Person, 'name')) # -> True
print(hasattr(Person, 'age')) # -> False26. getattr()
獲取對象的屬性值。
class Person:
name = 'Alice'
person = Person()
name_val = getattr(person, 'name') # -> 'Alice'27. callable()
檢查一個對象是否可以被調用(如函數、方法)。
def my_func(): pass
print(callable(my_func)) # -> True
print(callable(123)) # -> False五、基礎I/O與其它:程序的入口與輔助
這些是與外界交互和獲取幫助的基礎函數。
28. print()
將對象輸出到控制臺。
print("Hello, World!", end=' | ') # 使用 end 參數
print("Another message.")29. input()
從控制臺讀取用戶輸入,返回字符串。
name = input("Enter your name: ")
print(f"Hello, {name}!")30. help()
顯示對象的幫助信息。
# 在交互式環境中嘗試
# help(list)
# help(str.upper)


























