Python có nhiều tính năng "ngọt" (syntactic sugar) giúp code ngắn gọn, nhanh chóng, pythonic. Dưới đây là 10 thủ thuật thường dùng.
1. Lặp chuỗi/ký tự: "TP" * 4
print("I love Python " + "TP" * 4)
# I love Python TPTPTPTP2. Join list thành chuỗi đẹp
bikes = ['thunderbird', 'Pulsar', 'R15', 'Duke']
print("Bikes:", ", ".join(bikes))
# Bikes: thunderbird, Pulsar, R15, Duke
print("Bikes:", " and ".join(bikes))
# Bikes: thunderbird and Pulsar and R15 and Duke3. Duyệt song song nhiều list: zip()
bikes = ['thunderbird', 'Pulsar', 'R15', 'Duke']
speed = ['142', '135', '137', '145']
for bike, sp in zip(bikes, speed):
print(f"{bike}: {sp} km/h")4. Hoán đổi giá trị không cần biến tạm
a, b = 325, 976 a, b = b, a print(a, b) # 976 325
5. Đảo ngược sequence: [::-1]
s = "Hello World" print(s[::-1]) # dlroW olleH num = 934827165303 print(int(str(num)[::-1])) # 303561728439
6. Hàm trả về nhiều giá trị
def multiples():
return 1*3, 2*3, 3*3, 4*3, 5*3
v1, v2, v3, v4, v5 = multiples()
print(v1, v2, v3, v4, v5) # 3 6 9 12 157. Lấy index trong for loop: enumerate()
for i, bike in enumerate(bikes):
print(i, bike)
# 0 thunderbird
# 1 Pulsar
# 2 R15
# 3 Duke8. Slice list nâng cao
bikes = ['thunderbird', 'Pulsar', 'R15', 'Duke', 'S1000RR'] print(bikes[0:3]) # 3 phần tử đầu print(bikes[::2]) # cách 1 (index chẵn) print(bikes[::-1]) # đảo ngược print(bikes[::-2]) # đảo ngược cách 1
9. Chuyển string số thành list int: map(int, str.split())
s = "3 34 67 12 78" nums = list(map(int, s.split())) print(nums) # [3, 34, 67, 12, 78]
10. Làm phẳng list lồng (flatten): itertools.chain.from_iterable
import itertools dob = [[3, 30], [6, 12], [8, 17]] flat = list(itertools.chain.from_iterable(dob)) print(flat) # [3, 30, 6, 12, 8, 17] # Cách khác (Python 3.5+): flat = [item for sublist in dob for item in sublist]
Kết luận
Những thủ thuật này giúp code Python ngắn gọn, đọc dễ, chạy nhanh (vectorized/C-optimized). Hãy tập th quen dùng chúng trong code hàng ngày.