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

intersection_update() trong Python - Tìm phần tử chung của n mảng


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

  1. Khởi tạo res = set của list đầu tiên.
  2. Duyệt qua các list còn lại.
  3. Gọi res.intersection_update(current_list) để lọc phần tử chung.
  4. 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.