十個Python編程小技巧
1、列表推導式
列表推導式是一種在 Python 中創(chuàng)建列表的簡潔而富有表現(xiàn)力的方法。
你可以使用一行代碼來生成列表,而不是使用傳統(tǒng)的循環(huán)。
例如:
# Traditional approach
squared_numbers = []
for num in range(1, 6):
squared_numbers.append(num ** 2)
# Using list comprehension
squared_numbers = [num ** 2 for num in range(1, 6)]
2、enumerate 函數(shù)
迭代序列時,同時擁有索引和值通常很有用。enumerate 函數(shù)簡化了這個過程。
fruits = ['apple', 'banana', 'orange']
# Without enumerate
for i in range(len(fruits)):
print(i, fruits[i])
# With enumerate
for index, value in enumerate(fruits):
print(index, value)
3、zip 函數(shù)
zip 函數(shù)允許你同時迭代多個可迭代對象,創(chuàng)建相應(yīng)元素對。
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]
for name, age in zip(names, ages):
print(name, age)
4、with 語句
with 語句被用來包裹代碼塊的執(zhí)行,以便于對資源進行管理,特別是那些需要顯式地獲取和釋放的資源,比如文件操作、線程鎖、數(shù)據(jù)庫連接等。使用 with 語句可以使代碼更加簡潔,同時自動處理資源的清理工作,即使在代碼塊中發(fā)生異常也能保證資源正確地釋放。
with open('example.txt', 'r') as file:
content = file.read()
# Work with the file content
# File is automatically closed outside the "with" block
5、Set
集合是唯一元素的無序集合,這使得它們對于從列表中刪除重復項等任務(wù)非常有用。
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
6、使用 itertools 進行高效迭代
itertools 模塊提供了一組快速、節(jié)省內(nèi)存的工具來使用迭代器。例如,itertools.product 生成輸入可迭代對象的笛卡爾積。
import itertools
colors = ['red', 'blue']
sizes = ['small', 'large']
combinations = list(itertools.product(colors, sizes))
print(combinations)
7、用于代碼可重用性的裝飾器
裝飾器允許你修改或擴展函數(shù)或方法的行為。它們提高代碼的可重用性和可維護性。
def logger(func):
def wrapper(*args, **kwargs):
print(f'Calling function {func.__name__}')
result = func(*args, **kwargs)
print(f'Function {func.__name__} completed')
return result
return wrapper
@logger
def add(a, b):
return a + b
result = add(3, 5)
8、collections 模塊
Python 的 collections 模塊提供了超出內(nèi)置類型的專門數(shù)據(jù)結(jié)構(gòu)。
例如,Counter 幫助計算集合中元素的出現(xiàn)次數(shù)。
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(words)
print(word_count)
9、使用 “f-strings” 進行字符串格式化
Python 3.6 中引入的 f-string 提供了一種簡潔易讀的字符串格式設(shè)置方式。
name = 'Alice'
age = 30
print(f'{name} is {age} years old.')
10、虛擬環(huán)境
虛擬環(huán)境有助于隔離項目依賴關(guān)系,防止不同項目之間發(fā)生沖突。
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# Install dependencies within the virtual environment
pip install package_name
# Deactivate the virtual environment
deactivate