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

Hàm intersection() trong Python


set1.intersection(set2, set3, ...) trả về set mới chứa các phần tử chung của tất cả các set truyền vào. Không sửa đổi set gốc.

Cú pháp

set1.intersection(*others) -> set
# Tương đương: set1 & set2 & set3 ...

Ví dụ

set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'t','u','t'}

# Giao 2 set
print("set1 ∩ set2:", set_1.intersection(set_2))
# Giao 3 set
print("set1 ∩ set2 ∩ set3:", set_1.intersection(set_2, set_3))

Kết quả

set1 ∩ set2: {'i', 'o', 't'}
set1 ∩ set2 ∩ set3: {'t'}

intersection() vs intersection_update()

Chấp nhận iterable khác

# intersection() chấp nhận bất kỳ iterable nào
list_a = [1,2,3,4]
list_b = [3,4,5,6]
print(set(list_a).intersection(list_b))  # {3, 4}

Kết luận

intersection() tìm giao của nhiều tập hợp, trả về set mới, không thay đổi gốc. Dùng toán tử & cho code ngắn gọn.

Phương thứcTrả vềSửa đổi set gốc?
intersection()Set mớiKhông
intersection_update()NoneCó (in-place)