Trong hướng dẫn này, ta viết chương trình gom tất cả tuple từ list có cùng phần tử thứ hai. Xem ví dụ để hiểu rõ.
Đầu vào
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')] Đầu ra
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]} Ta phải gom nhóm tuple từ list. Các bước giải quyết:
- Khởi tạo list với các tuple cần thiết.
- Tạo dictionary rỗng.
- Lặp qua list các tuple.
- Kiểm tra phần tử thứ hai của tuple đã có trong dictionary chưa.
- Nếu có, thêm tuple hiện tại vào list của nó.
- Ngược lại, khởi tạo key với list chứa tuple hiện tại.
- Cuối cùng, nhận dictionary với các sửa đổi cần thiết.
Ví dụ
# Khởi tạo list với tuple
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
# Dict rỗng
result = {}
# Lặp qua list tuple
for tup in tuples:
# Kiểm tra phần tử tuple trong dict
if tup[1] in result:
# Thêm tuple hiện tại vào dict
result[tup[1]].append(tup)
else:
# Khởi tạo key với list
result[tup[1]] = [tup]
# In kết quả
print(result) Kết quả
Nếu chạy mã trên, bạn sẽ nhận được kết quả sau.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]} Ta bỏ qua điều kiện if trong chương trình trên dùng defaultdict. Hãy giải quyết bằng defaultdict.
Ví dụ
# Import defaultdict từ collections
from collections import defaultdict
# Khởi tạo list với tuple
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
# Dict rỗng với defaultdict
result = defaultdict(list)
# Lặp qua list tuple
for tup in tuples:
result[tup[1]].append(tup)
# In kết quả
print(dict(result)) Kết quả
Nếu chạy mã trên, bạn sẽ nhận được kết quả sau.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]} Kết luận
Bạn có thể giải quyết theo nhiều cách khác. Ở đây ta thấy hai cách. Nếu có thắc mắc, hãy đề cập ở phần bình luận.