Python Set intersection() 方法
示例
返回一個集合,其中包含同時存在於集合 x
和集合 y
中的元素
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
自己動手試一試 »
定義和用法
intersection()
方法返回一個包含兩個或多個集合之間相似項的集合。
含義:返回的集合僅包含同時存在於兩個集合中的項,如果比較的是三個或更多集合,則包含所有集合中都存在的項。
作為快捷方式,您可以使用 &
運算子代替,請參閱下面的示例。
語法
set.intersection(set1, set2 ... 等)
引數值
引數 | 描述 |
---|---|
set1 | 必需。用於查詢相等元素的集合 |
set2 | 可選。要搜尋相等項的另一個集合。 您可以比較任意數量的集合。 使用逗號分隔集合 |
更短的語法
set & set1 & set2 ... 等
引數值
引數 | 描述 |
---|---|
set1 | 必需。用於查詢相等元素的集合 |
set2 | 可選。要搜尋相等項的另一個集合。 您可以比較任意數量的集合。 使用 & (和運算子) 分隔集合。請參見下面的示例。 |
更多示例
示例
使用 &
作為 intersection()
的快捷方式
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x & y
print(z)
自己動手試一試 »
示例
合併 3 個集合,並返回一個包含這 3 個集合中都存在的項的集合
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
自己動手試一試 »
示例
使用 &
運算符合並 3 個集合
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x & y & z
print(result)
自己動手試一試 »