__name__ == '__main__'
Xác định module hiện tại đang được thực thi trực tiếp hay được nhập vào module khác.
def execute_app() -> None:
print("Chương trình khởi động")
if __name__ == '__main__':
execute_app()
Mã sau đây luôn chạy dù file được thực thi trực tiếp hay nhập vào:
print("Mã này luôn chạy")
Chức năng next
Hàm next nhận một iterator và giá trị mặc định, trả về phần tử tiếp theo hoặc giá trị mặc định nếu hết phần tử.
data = [5, 8, 12, 6, 9]
data2 = [5, 8, 6, 9]
first_greater = next((x for x in data if x > 10), None) # 12
index_found = next((i for i, x in enumerate(data) if x > 10), -1) # 2
map và filter
Sử dụng map cho biến đổi và filter cho lọc, hoặc dùng list comprehension.
numbers = [2, 4, 6, 8, 10]
even_squares = [x * x for x in numbers if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
squares_mapped = list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, numbers)))
print(squares_mapped) # [4, 16, 36, 64, 100]
all và any
all kiểm tra tất cả phần tử đều True; any kiểm tra ít nhất một phần tử True.
values = [2, 4, 7, 9]
all_even = all(x % 2 == 0 for x in values) # False
any_even = any(x % 2 == 0 for x in values) # True
reverse và reversed
arr[::-1] tạo bản sao đảo ngược; reversed(arr) trả iterator; arr.reverse() đảo ngược trực tiếp.
arr = [10, 20, 30, 40]
reversed_copy = arr[::-1] # [40, 30, 20, 10]
reversed_iter = list(reversed(arr)) # [40, 30, 20, 10]
arr.reverse()
print(arr) # [40, 30, 20, 10]
zip
Kết hợp các phần tử từ nhiều iterable theo chỉ số.
chars = ['x', 'y', 'z']
indices = [10, 20, 30]
zipped = list(zip(chars, indices)) # [('x', 10), ('y', 20), ('z', 30)]
for c, idx in zip(chars, indices):
print(c, idx)
print(dict(zip(chars, indices))) # {'x': 10, 'y': 20, 'z': 30}
Thao tác trên dictionary
Sử dụng get truy cập an toàn; setdefault chèn nếu không tồn tại.
dict_a = {'key1': 'val1', 'key2': 'val2'}
val = dict_a.get('key3', 'default') # 'default'
print(val, dict_a) # 'default' {'key1': 'val1', 'key2': 'val2'}
val = dict_a.setdefault('key1', 'new') # 'val1'
print(val, dict_a) # 'val1' {'key1': 'val1', 'key2': 'val2'}
val = dict_a.setdefault('key3', 'new') # 'new'
print(val, dict_a) # 'new' {'key1': 'val1', 'key2': 'val2', 'key3': 'new'}
# Kết hợp dictionary
dict_b = {'key1': 'val3', 'key4': 'val4'}
merged = {**dict_a, **dict_b}
print(merged) # {'key1': 'val3', 'key2': 'val2', 'key3': 'new', 'key4': 'val4'}
reduce
reduce áp dụng hàm tuần tự lên các phần tử của iterable.
from functools import reduce
num_list = [5, 3, 8, 2, 7]
total = reduce(lambda a, b: a + b, num_list) # 25
total_with_start = reduce(lambda a, b: a + b, num_list, 5) # 30
max_val = reduce(lambda a, b: a if a > b else b, num_list) # 8
min_val = reduce(lambda a, b: a if a < b else b, num_list) # 2