💝💝💝歡迎蒞臨我的博客,很高興能夠在這里和您見面!希望您在這里可以感受到一份輕松愉快的氛圍,不僅可以獲得有趣的內容和知識,也可以暢所欲言、分享您的想法和見解。
持續學習,不斷總結,共同進步,為了踏實,做好當下事兒~
非常期待和您一起在這個小小的網絡世界里共同探索、學習和成長。💝💝💝 ?? 歡迎訂閱本專欄 ??
💖The Start💖點點關注,收藏不迷路💖 |
📒文章目錄
- 1. 引言:Python內置函數的重要性
- 內置函數的優勢:
- 適用場景:
- 學習目標:
- 2. 基礎操作函數
- 2.1 len():獲取對象長度
- 2.2 range():生成整數序列
- 2.3 enumerate():為可迭代對象添加索引
- 3. 函數式編程工具
- 3.1 map():對可迭代對象應用函數
- 3.2 filter():過濾可迭代對象
- 3.3 reduce():累積計算
- 4. 輸入輸出函數
- 4.1 open():打開文件
- 4.2 print():輸出內容
- 4.3 input():獲取用戶輸入
- 5. 元編程相關函數
- 5.1 type():獲取對象類型
- 5.2 isinstance():檢查對象類型
- 5.3 hasattr():檢查對象屬性
- 6. 其他常用內置函數
- 6.1 zip():合并多個可迭代對象
- 6.2 sorted():排序可迭代對象
Python作為一門高效且功能強大的編程語言,其內置函數是開發者日常編程中不可或缺的工具。掌握這些內置函數不僅能提升代碼效率,還能使代碼更加簡潔、Pythonic。本文將系統梳理30個常用內置函數,涵蓋數據類型操作、函數式編程、輸入輸出和元編程等核心功能,每個函數均配有語法說明、參數詳解和實用案例,幫助開發者深入理解并靈活運用。
1. 引言:Python內置函數的重要性
Python內置函數是Python解釋器自帶的函數,無需導入任何模塊即可直接使用。它們經過高度優化,執行效率高,是Python編程中不可或缺的一部分。掌握這些內置函數,不僅能提升開發效率,還能使代碼更加簡潔、優雅,符合Python的設計哲學。
內置函數的優勢:
- 無需導入:直接調用,減少代碼冗余。
- 高效執行:底層由C語言實現,運行速度快。
- 廣泛適用:覆蓋數據處理、函數式編程、文件操作、元編程等多個領域。
適用場景:
內置函數廣泛應用于日常開發中,例如:
- 數據處理:使用
len()
、range()
等快速操作數據。 - 函數式編程:利用
map()
、filter()
等實現簡潔的邏輯。 - 文件操作:通過
open()
、print()
等處理輸入輸出。 - 元編程:借助
type()
、isinstance()
等動態操作對象。
學習目標:
通過本文,您將系統掌握30個核心內置函數的語法、參數和實際應用,能夠寫出更高效、Pythonic的代碼。
2. 基礎操作函數
基礎操作函數是Python中最常用的一類內置函數,用于處理數據的基本操作,如獲取長度、生成序列、添加索引等。
2.1 len():獲取對象長度
len()
函數用于返回對象的長度或元素個數,適用于所有可迭代對象,如列表、字符串、元組、字典等。
- 語法:
len(object)
- 參數:
object
:需要計算長度的可迭代對象。
- 返回值:整數,表示對象的長度。
示例代碼:
# 計算列表長度
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 輸出:5# 計算字符串長度
my_string = "Hello, World!"
print(len(my_string)) # 輸出:13# 計算字典鍵值對數量
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(len(my_dict)) # 輸出:3
注意事項:
- 對于自定義對象,可以通過實現
__len__()
方法來自定義len()
的行為。
2.2 range():生成整數序列
range()
函數用于生成一個整數序列,常用于循環操作。
- 語法:
range(start, stop, step)
- 參數:
start
:序列起始值(可選,默認為0)。stop
:序列終止值(不包含該值)。step
:步長(可選,默認為1)。
- 返回值:一個不可變的序列對象,通常通過
list()
轉換為列表使用。
示例代碼:
# 生成0到4的整數序列
print(list(range(5))) # 輸出:[0, 1, 2, 3, 4]# 生成2到10的偶數序列
print(list(range(2, 11, 2))) # 輸出:[2, 4, 6, 8, 10]# 逆序生成序列
print(list(range(5, 0, -1))) # 輸出:[5, 4, 3, 2, 1]
應用場景:
- 循環遍歷:
for i in range(10):
- 生成索引:與
len()
結合使用,遍歷列表索引。
2.3 enumerate():為可迭代對象添加索引
enumerate()
函數用于為可迭代對象添加索引,返回一個枚舉對象,其中每個元素是(索引,值)元組。
- 語法:
enumerate(iterable, start=0)
- 參數:
iterable
:可迭代對象,如列表、字符串等。start
:索引的起始值(可選,默認為0)。
- 返回值:枚舉對象,可通過
list()
轉換為列表。
示例代碼:
fruits = ['apple', 'banana', 'cherry']# 默認起始索引為0
print(list(enumerate(fruits))) # 輸出:[(0, 'apple'), (1, 'banana'), (2, 'cherry')]# 設置起始索引為1
print(list(enumerate(fruits, start=1))) # 輸出:[(1, 'apple'), (2, 'banana'), (3, 'cherry')]# 在循環中使用
for index, value in enumerate(fruits):print(f"Index: {index}, Value: {value}")
優勢:
- 簡化代碼:無需手動維護索引變量。
- 提高可讀性:直接獲取索引和值。
3. 函數式編程工具
函數式編程是一種編程范式,Python通過內置函數如map()
、filter()
和reduce()
提供支持,使代碼更簡潔、表達力更強。
3.1 map():對可迭代對象應用函數
map()
函數將指定函數應用于可迭代對象的每個元素,返回一個迭代器。
- 語法:
map(function, iterable)
- 參數:
function
:要應用的函數。iterable
:一個或多個可迭代對象。
- 返回值:map對象(迭代器),可通過
list()
轉換為列表。
示例代碼:
# 將列表中的每個元素平方
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # 輸出:[1, 4, 9, 16]# 使用內置函數
words = ["hello", "world"]
upper_words = list(map(str.upper, words))
print(upper_words) # 輸出:['HELLO', 'WORLD']# 多個可迭代對象
a = [1, 2, 3]
b = [4, 5, 6]
sums = list(map(lambda x, y: x + y, a, b))
print(sums) # 輸出:[5, 7, 9]
應用場景:
- 數據轉換:將一組數據轉換為另一種形式。
- 批量處理:對每個元素執行相同操作。
3.2 filter():過濾可迭代對象
filter()
函數用于過濾可迭代對象,保留使函數返回True的元素。
- 語法:
filter(function, iterable)
- 參數:
function
:過濾函數,返回布爾值。iterable
:可迭代對象。
- 返回值:filter對象(迭代器),可通過
list()
轉換為列表。
示例代碼:
# 過濾偶數
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 輸出:[2, 4, 6]# 過濾非空字符串
words = ["hello", "", "world", None, " "]
non_empty = list(filter(None, words)) # None作為函數時,過濾假值
print(non_empty) # 輸出:['hello', 'world', ' ']# 自定義過濾函數
def is_positive(x):return x > 0positives = list(filter(is_positive, [-2, -1, 0, 1, 2]))
print(positives) # 輸出:[1, 2]
注意事項:
- 如果
function
為None
,則過濾掉所有假值(如False、0、“”、None等)。
3.3 reduce():累積計算
reduce()
函數對可迭代對象中的元素進行累積計算,通過指定函數逐步合并元素。
- 語法:
reduce(function, iterable[, initial])
- 參數:
function
:累積函數,接受兩個參數。iterable
:可迭代對象。initial
:初始值(可選)。
- 返回值:累積計算的結果。
注意:reduce()
函數在Python 3中移至functools
模塊,需先導入。
示例代碼:
from functools import reduce# 計算列表元素的乘積
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 輸出:24# 使用初始值
sum_with_initial = reduce(lambda x, y: x + y, numbers, 10)
print(sum_with_initial) # 輸出:20# 查找最大值
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print(max_value) # 輸出:4
應用場景:
- 累積計算:如求和、求積、找最大值等。
- 數據聚合:逐步合并多個數據項。
4. 輸入輸出函數
輸入輸出(I/O)函數用于處理程序與外部環境的數據交互,如讀寫文件、打印輸出、獲取用戶輸入等。
4.1 open():打開文件
open()
函數用于打開文件,返回文件對象,支持讀寫操作。
- 語法:
open(file, mode='r', encoding=None)
- 參數:
file
:文件路徑(字符串)。mode
:打開模式,如'r'
(讀)、'w'
(寫)、'a'
(追加)等。encoding
:編碼方式,如'utf-8'
。
- 返回值:文件對象。
示例代碼:
# 讀取文件內容
with open('example.txt', 'r', encoding='utf-8') as f:content = f.read()print(content)# 寫入文件
with open('output.txt', 'w', encoding='utf-8') as f:f.write("Hello, World!")# 追加內容
with open('output.txt', 'a', encoding='utf-8') as f:f.write("\nAppended text.")
常用模式:
'r'
:讀取(默認)。'w'
:寫入(覆蓋原有內容)。'a'
:追加。'b'
:二進制模式,如'rb'
。
最佳實踐:
- 使用
with
語句確保文件正確關閉。 - 指定編碼以避免亂碼問題。
4.2 print():輸出內容
print()
函數用于將內容輸出到標準輸出(如控制臺)。
- 語法:
print(*objects, sep=' ', end='\n')
- 參數:
objects
:一個或多個要輸出的對象。sep
:分隔符(默認為空格)。end
:結束符(默認為換行符)。
- 返回值:無。
示例代碼:
# 基本輸出
print("Hello, World!") # 輸出:Hello, World!# 輸出多個對象
print("Hello", "World", sep="-") # 輸出:Hello-World# 自定義結束符
print("Hello", end=" ")
print("World") # 輸出:Hello World# 輸出到文件
with open('output.txt', 'w') as f:print("Hello, File!", file=f)
高級用法:
- 格式化輸出:結合f-string或
format()
方法。 - 重定向輸出:通過
file
參數輸出到文件。
4.3 input():獲取用戶輸入
input()
函數用于從標準輸入(如鍵盤)獲取用戶輸入。
- 語法:
input([prompt])
- 參數:
prompt
:提示信息(可選)。
- 返回值:字符串,用戶輸入的內容。
示例代碼:
# 基本輸入
name = input("Enter your name: ")
print(f"Hello, {name}!")# 輸入數值
age = int(input("Enter your age: "))
print(f"You are {age} years old.")# 輸入多個值
data = input("Enter two numbers separated by space: ").split()
a, b = map(int, data)
print(f"Sum: {a + b}")
注意事項:
- 輸入的內容總是字符串類型,需根據需要轉換。
- 處理異常輸入,避免程序崩潰。
5. 元編程相關函數
元編程涉及在運行時操作程序本身,Python提供了一系列內置函數來支持元編程,如檢查類型、屬性等。
5.1 type():獲取對象類型
type()
函數用于獲取對象的類型。
- 語法:
type(object)
- 參數:
object
:任意對象。
- 返回值:對象的類型。
示例代碼:
# 獲取內置類型
print(type(42)) # 輸出:<class 'int'>
print(type("hello")) # 輸出:<class 'str'>
print(type([1, 2, 3])) # 輸出:<class 'list'># 自定義類
class MyClass:passobj = MyClass()
print(type(obj)) # 輸出:<class '__main__.MyClass'># 動態創建類
MyDynamicClass = type('MyDynamicClass', (), {})
instance = MyDynamicClass()
print(type(instance)) # 輸出:<class '__main__.MyDynamicClass'>
應用場景:
- 類型檢查:在運行時確定對象類型。
- 動態創建類:使用
type()
動態生成類。
5.2 isinstance():檢查對象類型
isinstance()
函數用于檢查對象是否為指定類型的實例。
- 語法:
isinstance(object, classinfo)
- 參數:
object
:要檢查的對象。classinfo
:類型或類型元組。
- 返回值:布爾值,表示對象是否屬于指定類型。
示例代碼:
# 檢查內置類型
num = 42
print(isinstance(num, int)) # 輸出:True
print(isinstance(num, str)) # 輸出:False# 檢查多個類型
print(isinstance(num, (int, float))) # 輸出:True# 檢查繼承關系
class Parent:passclass Child(Parent):passobj = Child()
print(isinstance(obj, Parent)) # 輸出:True
優勢:
- 支持繼承關系檢查。
- 可同時檢查多個類型。
5.3 hasattr():檢查對象屬性
hasattr()
函數用于檢查對象是否具有指定屬性。
- 語法:
hasattr(object, name)
- 參數:
object
:要檢查的對象。name
:屬性名稱(字符串)。
- 返回值:布爾值,表示對象是否具有該屬性。
示例代碼:
class MyClass:def __init__(self):self.value = 42def method(self):passobj = MyClass()# 檢查屬性
print(hasattr(obj, 'value')) # 輸出:True
print(hasattr(obj, 'method')) # 輸出:True
print(hasattr(obj, 'unknown')) # 輸出:False# 檢查模塊屬性
import math
print(hasattr(math, 'sqrt')) # 輸出:True
應用場景:
- 動態屬性訪問:在訪問屬性前先檢查是否存在。
- 插件系統:檢查對象是否支持特定方法。
6. 其他常用內置函數
除了上述分類,Python還提供了許多其他實用的內置函數,如zip()
、sorted()
、max()
和min()
等。
6.1 zip():合并多個可迭代對象
zip()
函數用于將多個可迭代對象中的元素按順序配對,返回一個迭代器。
- 語法:
zip(*iterables)
- 參數:
iterables
:多個可迭代對象。
- 返回值:zip對象(迭代器),可通過
list()
轉換為元組列表。
示例代碼:
# 基本用法
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
combined = list(zip(names, scores))
print(combined) # 輸出:[('Alice', 85), ('Bob', 90), ('Charlie', 78)]# 長度不一致時,以最短的為準
ages = [25, 30]
result = list(zip(names, ages))
print(result) # 輸出:[('Alice', 25), ('Bob', 30)]# 解壓
pairs = [('a', 1), ('b', 2), ('c', 3)]
unzipped = list(zip(*pairs))
print(unzipped) # 輸出:[('a', 'b', 'c'), (1, 2, 3)]
應用場景:
- 數據配對:將多個列表的元素一一對應。
- 矩陣轉置:通過
zip(*matrix)
實現。
6.2 sorted():排序可迭代對象
sorted()
函數用于對可迭代對象進行排序,返回一個新列表。
- 語法:
sorted(iterable, key=None, reverse=False)
- 參數:
iterable
:可迭代對象。key
:排序鍵函數(可選)。reverse
:是否逆序排序(可選,默認為False)。
- 返回值:排序后的新列表。
示例代碼:
# 基本排序
numbers = [3, 1, 4, 1, 5, 9]
print(sorted(numbers)) # 輸出:[1, 1, 3, 4, 5, 9]# 逆序排序
print(sorted(numbers, reverse=True)) # 輸出:[9---🔥🔥🔥道阻且長,行則將至,讓我們一起加油吧!🌙🌙🌙<div class="table-box"><table width="100%"><tbody><tr><td width="50%"><div align="center"><font color="#E73B3E"><em>💖The Start💖點點關注,收藏不迷路💖<em></em></em></font></div></td></tr></tbody></table>
</div>---