Khi cần tìm set trùng lặp trong list of sets, dùng Counter và frozenset.
Ví dụ
from collections import Counter
my_list = [{4, 8, 6, 1}, {6, 4, 1, 8}, {1, 2, 6, 2}, {1, 4, 2}, {7, 8, 9}]
print("The list is:")
print(my_list)
my_freq = Counter(frozenset(sub) for sub in my_list)
my_result = []
for key, value in my_freq.items():
if value > 1:
my_result.append(key)
print("The result is:")
print(my_result)
Đầu ra
The list is: [{8, 1, 4, 6}, {8, 1, 4, 6}, {1, 2, 6}, {1, 2, 4}, {8, 9, 7}]
The result is: [frozenset({8, 1, 4, 6})]
Giải thích
- Định nghĩa list of sets, hiển thị.
- Lặp qua dùng
frozenset(vì set không hashable) vàCounter. - Đếm tần suất mỗi set.
- Nếu tần suất > 1, thêm vào kết quả.
- Hiển thị.