set.intersection_update(*others) cập nhật set gốc, chỉ giữ lại phần tử xuất hiện trong tất cả các set/iterable truyền vào.
Thuật toán
- Khởi tạo
res= set của list đầu tiên. - Duyệt qua các list còn lại.
- Gọi
res.intersection_update(current_list)để lọc phần tử chung. - Trả về
list(res).
Ví dụ
def common_elements(arrays):
if not arrays:
return []
res = set(arrays[0])
for arr in arrays[1:]:
res.intersection_update(arr)
return list(res)
# Chương trình chính
if __name__ == "__main__":
nested_list = [
['t','u','o','r','i','a','l'],
['p','o','i','n','t'],
['t','u','o','r','i','a','l'],
['p','y','t','h','o','n']
]
out = common_elements(nested_list)
if out:
print("Phần tử chung:", out)
else:
print("Không có phần tử chung")
Kết quả
Phần tử chung: ['o', 't']
Phương pháp thay thế (functional)
from functools import reduce
def common_elements_v2(arrays):
if not arrays:
return []
return list(reduce(lambda a, b: a & b, map(set, arrays)))
Kết luận
intersection_update() hiệu quả để tìm giao của nhiều tập hợp, sửa đổi in-place, tiết kiệm bộ nhớ so với tạo set mới liên tục.