Python 20 個內(nèi)置函數(shù)的隱藏技巧,讓你成為代碼大師
作者:用戶007
本文將深入探討 20 個常用 Python 內(nèi)置函數(shù)的隱藏技巧和最佳實踐,幫助你在日常編碼中更加高效。
Python以其簡潔易學著稱,而其強大的內(nèi)置函數(shù)更是這一特性的體現(xiàn)。然而,許多開發(fā)者只會使用這些函數(shù)的基礎(chǔ)功能,忽視了它們的高級用法。本文將深入探討20個常用Python內(nèi)置函數(shù)的隱藏技巧和最佳實踐,幫助你在日常編碼中更加高效。

一、20個內(nèi)置函數(shù)的深度應(yīng)用
1. enumerate():遍歷時同時獲取索引
# 基礎(chǔ)用法
for idx, item in enumerate(['a', 'b', 'c']):
print(f"{idx}: {item}")
# 指定起始索引
for idx, item in enumerate(['a', 'b', 'c'], start=1):
print(f"{idx}: {item}")
# 獲取索引-值對的字典
d = {idx: item for idx, item in enumerate(['a', 'b', 'c'])}
# 反向索引
for idx, item in enumerate(reversed(['a', 'b', 'c'])):
print(idx, item)2. zip():多個序列并行遍歷
# 基本用法
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 28]
for name, age in zip(names, ages):
print(f"{name}: {age}")
# 解包多個列表
a, b, c = zip(*[(1, 2, 3), (4, 5, 6)])
# 創(chuàng)建字典
d = dict(zip(names, ages))
# 處理不同長度的序列
from itertools import zip_longest
for name, age in zip_longest(names, ages, fillvalue='Unknown'):
print(name, age)3. map():函數(shù)式編程的優(yōu)雅方式
# 基礎(chǔ)用法
numbers = ['1', '2', '3', '4', '5']
result = list(map(int, numbers))
# 使用lambda函數(shù)
squared = list(map(lambda x: x ** 2, range(10)))
# 多序列映射
a = [1, 2, 3]
b = [4, 5, 6]
result = list(map(lambda x, y: x + y, a, b))
# 使用自定義函數(shù)
defprocess(x):
return x * 2 + 1
result = list(map(process, range(10)))
# 性能優(yōu)化:避免不必要的list轉(zhuǎn)換
result = map(int, ['1', '2', '3']) # 返回迭代器,按需消費4. filter():優(yōu)雅的數(shù)據(jù)篩選
# 基礎(chǔ)用法
numbers = range(10)
evens = list(filter(lambda x: x % 2 == 0, numbers))
# 與None的特殊用法
values = [0, 1, False, 2, '', 'hello', [], [1, 2]]
truthy = list(filter(None, values)) # [1, 2, 'hello', [1, 2]]
# 自定義過濾函數(shù)
defis_prime(n):
if n < 2:
returnFalse
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
returnFalse
returnTrue
primes = list(filter(is_prime, range(20)))5. reduce():聚合序列
from functools import reduce
# 求和(雖然sum()更簡單,但演示reduce的用法)
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
# 求最大值
max_val = reduce(lambda x, y: x if x > y else y, [3, 1, 4, 1, 5, 9])
# 矩陣乘法
import numpy as np
matrices = [np.random.rand(2, 2) for _ in range(3)]
result = reduce(lambda x, y: np.dot(x, y), matrices)
# 嵌套字典合并
dicts = [{'a': 1}, {'b': 2}, {'c': 3}]
merged = reduce(lambda x, y: {**x, **y}, dicts)6. sorted():強大的排序函數(shù)
# 基礎(chǔ)排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_nums = sorted(numbers)
# 自定義排序鍵
students = [('Alice', 25), ('Bob', 30), ('Charlie', 28)]
by_age = sorted(students, key=lambda x: x[1])
by_name = sorted(students, key=lambda x: x[0])
# 多鍵排序
by_age_then_name = sorted(students, key=lambda x: (x[1], x[0]))
# 反向排序
descending = sorted(numbers, reverse=True)
# 穩(wěn)定排序特性
data = [(1, 'a'), (1, 'b'), (2, 'c'), (1, 'd')]
sorted_data = sorted(data, key=lambda x: x[0]) # 保持相同key的原順序7. any()和all():邏輯判斷
# any():至少一個為真
numbers = [0, 0, 1, 0]
if any(numbers):
print("至少有一個非零數(shù)")
# 檢查任意條件滿足
users = [{'active': False}, {'active': False}, {'active': True}]
if any(user['active'] for user in users):
print("至少有一個活躍用戶")
# all():全部為真
numbers = [1, 2, 3, 4, 5]
if all(x > 0for x in numbers):
print("所有數(shù)都是正數(shù)")
# 檢查所有條件滿足
emails = ['user@example.com', 'admin@example.com']
if all('@'in email for email in emails):
print("所有都是有效的郵箱格式")
# 空序列的特殊行為
any([]) # False
all([]) # True8. sum():靈活的求和
# 基礎(chǔ)求和
total = sum([1, 2, 3, 4, 5])
# 指定初始值
total = sum([1, 2, 3], start=100) # 106
# 求和生成器表達式
total = sum(x ** 2for x in range(10))
# 多維列表展平求和
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = sum(sum(row) for row in matrix)
# 自定義對象求和(需實現(xiàn)__add__)
from datetime import timedelta
durations = [timedelta(hours=1), timedelta(hours=2)]
total_duration = sum(durations, timedelta())9. min()和max():尋找極值
# 基礎(chǔ)用法
numbers = [3, 1, 4, 1, 5, 9]
smallest = min(numbers)
largest = max(numbers)
# 多個參數(shù)
result = max(10, 20, 30, 40)
# 自定義排序鍵
students = [('Alice', 25), ('Bob', 30), ('Charlie', 28)]
youngest = min(students, key=lambda x: x[1])
oldest = max(students, key=lambda x: x[1])
# 獲取多個最值
import heapq
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
top_3 = heapq.nlargest(3, numbers)
bottom_3 = heapq.nsmallest(3, numbers)
# 處理空序列
from itertools import chain
try:
result = min([])
except ValueError:
print("序列為空")10. isinstance():類型檢查的最佳實踐
# 基礎(chǔ)用法
x = 10
isinstance(x, int) # True
# 檢查多種類型
value = 3.14
isinstance(value, (int, float)) # True
# 檢查自定義類
classAnimal:
pass
classDog(Animal):
pass
dog = Dog()
isinstance(dog, Dog) # True
isinstance(dog, Animal) # True(繼承關(guān)系)
# 避免類型檢查陷阱
# 不推薦:type(x) == int
# 推薦:isinstance(x, int)
# 鴨式類型檢查替代方案
defprocess(obj):
if hasattr(obj, '__iter__'):
for item in obj:
print(item)11. getattr()和setattr():動態(tài)屬性訪問
# getattr:獲取屬性,提供默認值
classConfig:
debug = True
timeout = 30
config = Config()
debug = getattr(config, 'debug', False)
log_level = getattr(config, 'log_level', 'INFO')
# setattr:動態(tài)設(shè)置屬性
setattr(config, 'log_level', 'DEBUG')
setattr(config, 'new_attr', 'value')
# 動態(tài)創(chuàng)建對象的屬性
data = {'name': 'Alice', 'age': 25}
for key, value in data.items():
setattr(config, key, value)
# hasattr和getattr的組合
if hasattr(config, 'debug'):
value = getattr(config, 'debug')12. dir():探索對象的屬性
# 列出對象的所有屬性
classMyClass:
attr1 = 10
defmethod1(self):
pass
obj = MyClass()
all_attrs = dir(obj)
# 過濾私有屬性
public_attrs = [attr for attr in dir(obj) ifnot attr.startswith('_')]
# 探索模塊的公共接口
import json
json_attrs = [attr for attr in dir(json) ifnot attr.startswith('_')]
# 查看內(nèi)置函數(shù)
builtin_funcs = dir(__builtins__)13. vars()和__dict__:查看對象的名空間
# vars()返回對象的__dict__
classPerson:
def__init__(self, name, age):
self.name = name
self.age = age
person = Person('Alice', 25)
print(vars(person)) # {'name': 'Alice', 'age': 25}
# 獲取本地變量
deflocal_vars():
x = 10
y = 20
return vars()
print(local_vars()) # {'x': 10, 'y': 20}
# 動態(tài)更新對象屬性
updates = {'name': 'Bob', 'age': 30}
vars(person).update(updates)14. type():動態(tài)類型檢查和創(chuàng)建
# 基礎(chǔ)類型檢查
x = 10
type(x) == int
# 獲取對象的類型名稱
print(type(x).__name__) # 'int'
# 獲取完整的類型信息
print(type(x)) # <class 'int'>
# 動態(tài)創(chuàng)建類
MyClass = type('MyClass', (), {'attr': 10})
obj = MyClass()
print(obj.attr) # 10
# 動態(tài)創(chuàng)建繼承關(guān)系
BaseClass = type('BaseClass', (), {'method': lambda self: 'base'})
DerivedClass = type('DerivedClass', (BaseClass,), {'method': lambda self: 'derived'})
# 檢查是否是某個類的實例
isinstance(obj, MyClass) # True15. callable():檢查可調(diào)用性
# 檢查函數(shù)
defmy_func():
pass
callable(my_func) # True
# 檢查類(類本身是可調(diào)用的)
classMyClass:
pass
callable(MyClass) # True
# 檢查實現(xiàn)了__call__的對象
classCallable:
def__call__(self):
return"called"
obj = Callable()
callable(obj) # True
# 實際應(yīng)用
defexecute_if_callable(func, *args):
if callable(func):
return func(*args)
returnNone
result = execute_if_callable(lambda x: x * 2, 5)16. round():數(shù)值舍入的精妙用法
# 基礎(chǔ)舍入
round(3.7) # 4
round(3.14159, 2) # 3.14
# 舍入到最近的10
round(1234, -1) # 1230
round(1234, -2) # 1200
# 銀行家舍入(Python 3的默認行為)
round(2.5) # 2
round(3.5) # 4
# 格式化顯示vs真實舍入
x = 3.14159
f"{x:.2f}"# '3.14'(字符串顯示)
round(x, 2) # 3.14(真實值修改)
# 按百分比舍入
values = [0.1234, 0.5678, 0.9012]
percentages = [round(v * 100, 1) for v in values]17. hash():哈希函數(shù)的應(yīng)用
# 基礎(chǔ)哈希
hash('hello')
hash(42)
hash((1, 2, 3))
# 相同對象有相同的哈希值
hash('test') == hash('test') # True
# 集合和字典依賴hash
my_set = {1, 2, 3}
my_dict = {'key': 'value'}
# 自定義對象的hash
classPerson:
def__init__(self, name, age):
self.name = name
self.age = age
def__hash__(self):
return hash((self.name, self.age))
def__eq__(self, other):
return self.name == other.name and self.age == other.age
person1 = Person('Alice', 25)
person2 = Person('Alice', 25)
people_set = {person1, person2} # 集合會去重18. chr()和ord():字符編碼轉(zhuǎn)換
# ord():字符轉(zhuǎn)編碼
ord('A') # 65
ord('a') # 97
ord('中') # 20013
# chr():編碼轉(zhuǎn)字符
chr(65) # 'A'
chr(20013) # '中'
# 字符串編碼
text = 'Hello'
encoded = [ord(c) for c in text]
decoded = ''.join(chr(code) for code in encoded)
# ASCII編碼表
ascii_table = {chr(i): i for i in range(32, 127)}
# Unicode范圍處理
all_chinese = [chr(i) for i in range(0x4E00, 0x9FFF)]19. pow():指數(shù)運算的高效方式
# 基礎(chǔ)冪運算
pow(2, 3) # 8
pow(2, 10) # 1024
# 與**的區(qū)別
pow(2, 3) == 2 ** 3# True
# 模冪運算(密碼學常用)
pow(2, 100, 10**9 + 7) # 快速計算大數(shù)的模
# 比較性能
# pow(a, b, m) 比 a**b % m 更高效
# 負數(shù)指數(shù)
pow(2, -1) # 0.5
pow(10, -2) # 0.01
# 復數(shù)冪運算
pow(2j, 2) # (-4+0j)20. iter()和next():手動迭代控制
# iter():創(chuàng)建迭代器
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
# next():獲取下一個元素
next(iterator) # 1
next(iterator) # 2
# 處理StopIteration異常
try:
whileTrue:
print(next(iterator))
except StopIteration:
print("迭代完成")
# 創(chuàng)建自定義迭代器
classCountUp:
def__init__(self, max):
self.max = max
self.current = 0
def__iter__(self):
return self
def__next__(self):
if self.current < self.max:
self.current += 1
return self.current
else:
raise StopIteration
# iter()的雙參數(shù)形式
with open('file.txt') as f:
for line in iter(lambda: f.readline().strip(), ''):
print(line)二、結(jié)尾
這20個內(nèi)置函數(shù)看似簡單,但它們的組合使用能夠解決復雜的編程問題。關(guān)鍵是理解每個函數(shù)的本質(zhì)特性,特別是它們?nèi)绾闻c函數(shù)式編程范式相結(jié)合。
責任編輯:趙寧寧
來源:
Python數(shù)智工坊



































