溫馨提示×

在Python中如何使用set方法求交集

小樊
82
2024-09-16 11:45:19
欄目: 編程語言

在Python中,可以使用內(nèi)置的集合(set)類型來求兩個集合的交集。具體來說,可以使用 intersection 方法或者 & 運算符來實現(xiàn)這一目標(biāo)。下面是兩種方法的示例:

# 使用 intersection 方法
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set)  # 輸出: {3, 4}

# 使用 & 運算符
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1 & set2
print(intersection_set)  # 輸出: {3, 4}

在這兩個示例中,我們首先定義了兩個集合 set1set2,然后使用 intersection 方法或 & 運算符來求它們的交集。最后,我們打印出交集,得到結(jié)果 {3, 4}

0