Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Các mẹo và thủ thuật Python thiết yếu cho lập trình viên

Bài viết tổng hợp các thủ thuật Python hữu ích giúp giảm độ dài code và tối ưu hiệu suất, phù hợp cho lập trình thi đấu và phát triển thực tế.

1. Hoán đổi giá trị tại chỗ (In-Place Swapping)

x, y = 50, 70
print(x, y)  # 50 70
x, y = y, x  # Hoán đổi
print(x, y)  # 70 50

2. Nối list thành chuỗi

lst = ['What', 'a', 'fine', 'morning']
print(" ".join(lst))  # What a fine morning

3. Loại bỏ phần tử trùng lặp trong list

# Cách 1: Không giữ thứ tự
lst = [2, 4, 4, 9, 13, 4, 2]
new_lst = list(set(lst))
print(new_lst)  # [9, 2, 4, 13]

# Cách 2: Giữ nguyên thứ tự (Python 3.7+)
from collections import OrderedDict
lst = [2, 4, 4, 9, 13, 4, 2]
print(list(OrderedDict.fromkeys(lst).keys()))  # [2, 4, 9, 13]

# Cách 3: Python 3.7+ dict giữ thứ tự
print(list(dict.fromkeys(lst)))  # [2, 4, 9, 13]

4. Đảo ngược chuỗi

s = "Hello, World!"
print(s[::-1])  # !dlroW ,olleH

letters = "abcdefghijklmnopqrstuvwxyz"
print(letters[::-1])  # zyxwvutsrqponmlkjihgfedcba

5. Đảo ngược list

lst = [20, 40, 60, 80]
print(lst[::-1])  # [80, 60, 40, 20]

6. Chuyển vị ma trận 2D

matrix = [['a', 'b', 'c'], ['d', 'e', 'f']]
transMatrix = zip(*matrix)
print(list(transMatrix))  # [('a', 'd'), ('b', 'e'), ('c', 'f')]

7. Kiểm tra anagram

from collections import Counter

def is_anagram(str1, str2):
    return Counter(str1) == Counter(str2)

print(is_anagram('hello', 'ollhe'))  # True
print(is_anagram('Hello', 'hello'))  # False (phân biệt chữ hoa/thường)

8. Kiểm tra đối tượng (Inspect)

lst = [1, 3, 4, 7, 9]
print(dir(lst))  # Liệt kê tất cả phương thức/thuộc tính

9. Duyệt list với chỉ số (Enumerate)

lst = [20, 10, 40, 50, 30, 40]
for i, value in enumerate(lst):
    print(i, ':', value)
# 0 : 20
# 1 : 10
# 2 : 40
# 3 : 50
# 4 : 30
# 5 : 40

10. Tính giai thừa

import functools
result = (lambda s: functools.reduce(int.__mul__, range(1, s+1), 1))(5)
print(result)  # 120

11. Tạo dictionary từ hai sequence

x1 = ('Name', 'EmpId', 'Sector')
y1 = ('Zack', 4005, 'Finance')
print(dict(zip(x1, y1)))  # {'Name': 'Zack', 'EmpId': 4005, 'Sector': 'Finance'}