一文帶你掌握5個鮮為人知的Python內(nèi)置函數(shù)
作為Python開發(fā)者,我們經(jīng)常使用print()、len()、range()等常見內(nèi)置函數(shù)。但Python標準庫中還隱藏著許多強大卻被低估的內(nèi)置函數(shù),它們能讓你的代碼更簡潔、更高效、更Pythonic。今天,我將分享5個你可能不太熟悉,但絕對值得掌握的內(nèi)置函數(shù)。
1.any()和all()- 邏輯判斷的利器
為什么需要它們?
當你需要檢查一個序列中是否"存在某個條件"或"所有元素都滿足某個條件"時,any()和all()能讓你告別冗長的循環(huán)。
基本用法
# any(): 只要有一個為True,就返回True numbers = [0, 2, 4, 6, 8] has_odd = any(n % 2 != 0 for n in numbers) # False # all(): 所有元素都為True,才返回True all_positive = all(n > 0 for n in numbers) # False (0不是正數(shù))
實戰(zhàn)案例
場景1:表單驗證
# 傳統(tǒng)寫法
def validate_user(user):
if not user.get('name'):
return False
if not user.get('email'):
return False
if not user.get('age'):
return False
return True
# 使用 all() - 簡潔明了
def validate_user(user):
required_fields = ['name', 'email', 'age']
return all(user.get(field) for field in required_fields)
場景2:權限檢查
# 檢查用戶是否擁有任一管理員權限 permissions = ['read', 'write', 'delete'] admin_permissions = ['admin', 'superuser', 'delete'] is_admin = any(perm in admin_permissions for perm in permissions)
性能優(yōu)勢
any()和all()支持短路求值,一旦確定結果就立即返回,不會遍歷整個序列,在處理大數(shù)據(jù)集時效率顯著提升。
2.enumerate()- 告別手動計數(shù)
為什么需要它?
在遍歷列表時,如果既需要元素值又需要索引,enumerate()能讓你擺脫笨拙的計數(shù)器。
基本用法
fruits = ['apple', 'banana', 'cherry']
# 傳統(tǒng)寫法
index = 0
for fruit in fruits:
print(f"{index}: {fruit}")
index += 1
# 使用 enumerate() - 優(yōu)雅簡潔
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
進階技巧
自定義起始索引
# 從1開始編號(比如顯示排名)
for rank, player in enumerate(players, start=1):
print(f"第{rank}名: {player}")
同時獲取多個序列的索引和值
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 87, 92]
for i, (name, score) in enumerate(zip(names, scores)):
print(f"學生{i+1}: {name} - {score}分")
實戰(zhàn)案例:查找所有匹配項的位置
# 找出列表中所有偶數(shù)的索引 numbers = [1, 4, 7, 8, 10, 3, 6] even_indices = [i for i, n in enumerate(numbers) if n % 2 == 0] # 結果: [1, 3, 4, 6]
3.zip()- 并行處理多個序列
為什么需要它?
當你需要同時遍歷多個列表,或將多個列表"打包"在一起時,zip()是最佳選擇。
基本用法
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['Beijing', 'Shanghai', 'Shenzhen']
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age}歲, 來自{city}")
強大功能
1. 創(chuàng)建字典
keys = ['name', 'age', 'email']
values = ['Alice', 25, 'alice@example.com']
user_dict = dict(zip(keys, values))
# {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
2. 矩陣轉置
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = list(zip(*matrix))
# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
3. 成對處理相鄰元素
numbers = [1, 2, 3, 4, 5] # 計算相鄰元素的差值 differences = [b - a for a, b in zip(numbers, numbers[1:])] # [1, 1, 1, 1]
注意事項
zip()會在最短序列結束時停止,如果需要填充缺失值,可以使用itertools.zip_longest()。
4.divmod()- 一次性獲取商和余數(shù)
為什么需要它?
當你需要同時得到除法的商和余數(shù)時,divmod()比分別調用//和%更高效(只需要一次除法運算)。
基本用法
quotient, remainder = divmod(17, 5) # quotient = 3, remainder = 2
實戰(zhàn)案例
場景1:時間格式轉換
def seconds_to_time(seconds):
minutes, secs = divmod(seconds, 60)
hours, mins = divmod(minutes, 60)
return f"{hours:02d}:{mins:02d}:{secs:02d}"
print(seconds_to_time(3665)) # "01:01:05"
場景2:分頁計算
def calculate_pagination(total_items, items_per_page):
total_pages, extra = divmod(total_items, items_per_page)
if extra > 0:
total_pages += 1
return total_pages
pages = calculate_pagination(97, 10) # 10頁
場景3:貨幣換算
def convert_cents(total_cents):
dollars, cents = divmod(total_cents, 100)
return f"${dollars}.{cents:02d}"
print(convert_cents(1234)) # "$12.34"
性能對比
# 傳統(tǒng)方法(兩次運算) q = a // b r = a % b # divmod(一次運算) q, r = divmod(a, b) # 更快!
5.getattr()/setattr()/hasattr()- 動態(tài)屬性操作
為什么需要它們?
當你需要根據(jù)字符串動態(tài)訪問或修改對象屬性時,這三個函數(shù)能讓你的代碼更靈活、更具擴展性。
基本用法
class User:
def __init__(self):
self.name = "Alice"
self.age = 25
user = User()
# getattr(): 動態(tài)獲取屬性
name = getattr(user, 'name') # "Alice"
# 提供默認值避免AttributeError
email = getattr(user, 'email', 'N/A') # "N/A"
# setattr(): 動態(tài)設置屬性
setattr(user, 'email', 'alice@example.com')
# hasattr(): 檢查屬性是否存在
if hasattr(user, 'phone'):
print(user.phone)
實戰(zhàn)案例
場景1:配置管理
class Config:
def __init__(self):
self.debug = False
self.database = 'sqlite'
self.port = 8000
def update_config(config, updates):
"""根據(jù)字典批量更新配置"""
for key, value in updates.items():
if hasattr(config, key):
setattr(config, key, value)
else:
print(f"警告: 未知配置項 {key}")
config = Config()
update_config(config, {'debug': True, 'port': 9000, 'unknown': 'value'})
場景2:表單數(shù)據(jù)映射
class Product:
def __init__(self, **kwargs):
# 動態(tài)設置所有傳入的屬性
for key, value in kwargs.items():
setattr(self, key, value)
product = Product(name="Laptop", price=999, stock=50)
print(product.name) # "Laptop"
場景3:API響應處理
def safe_get_nested(obj, path, default=None):
"""安全地獲取嵌套屬性,例如 'user.profile.email'"""
keys = path.split('.')
for key in keys:
if hasattr(obj, key):
obj = getattr(obj, key)
else:
return default
return obj
# 使用示例
value = safe_get_nested(user, 'profile.settings.theme', 'light')
場景4:通用數(shù)據(jù)導出
def export_to_dict(obj, fields):
"""將對象的指定字段導出為字典"""
return {
field: getattr(obj, field, None)
for field in fields
}
user_data = export_to_dict(user, ['name', 'age', 'email'])
總結
這5個內(nèi)置函數(shù)看似簡單,卻能在實際開發(fā)中顯著提升代碼質量:
| 函數(shù) | 核心優(yōu)勢 | 適用場景 |
|---|---|---|
| any() / all() | 短路求值,簡化邏輯判斷 | 數(shù)據(jù)驗證、權限檢查 |
| enumerate() | 同時獲取索引和值 | 需要位置信息的遍歷 |
| zip() | 并行處理多個序列 | 數(shù)據(jù)合并、矩陣操作 |
| divmod() | 一次運算得到商和余數(shù) | 時間轉換、分頁計算 |
| getattr() 系列 | 動態(tài)屬性操作 | 配置管理、通用處理 |
最佳實踐建議:
- 可讀性優(yōu)先:雖然這些函數(shù)能讓代碼更簡潔,但不要為了炫技而犧牲可讀性
- 性能考量:在處理大數(shù)據(jù)集時,這些函數(shù)的性能優(yōu)勢會更加明顯
- 組合使用:這些函數(shù)可以互相配合,創(chuàng)造更強大的功能
- 了解限制:例如
zip()在不等長序列的行為,getattr()需要處理不存在屬性的情況
掌握這些函數(shù),你的Python代碼將更加Pythonic、高效和優(yōu)雅?,F(xiàn)在就去試試吧!
到此這篇關于一文帶你掌握5個鮮為人知的Python內(nèi)置函數(shù)的文章就介紹到這了,更多相關Python內(nèi)置函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
numpy array找出符合條件的數(shù)并賦值的示例代碼
本文主要介紹了numpy array找出符合條件的數(shù)并賦值的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05
Pycharm pyuic5實現(xiàn)將ui文件轉為py文件,讓UI界面成功顯示
這篇文章主要介紹了Pycharm pyuic5實現(xiàn)將ui文件轉為py文件,讓UI界面成功顯示,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python?Matplotlib通過plt.subplots創(chuàng)建子繪圖
這篇文章主要介紹了Python?Matplotlib通過plt.subplots創(chuàng)建子繪圖,plt.subplots調用后將會產(chǎn)生一個圖表和默認網(wǎng)格,與此同時提供一個合理的控制策略布局子繪圖,更多相關需要的朋友可以參考下面文章內(nèi)容2022-07-07

