Python 集合 intersection() 方法
實例
返回包含存在于集合 x 和集合 y 中的項目的集合:
x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z)
定義和用法
intersection() 方法返回包含兩個或更多集合之間相似性的集合。
含義:返回的集合僅包含兩個集合中都存在的項目,或者如果使用兩個以上的集合進行比較,則在所有集合中都存在。
語法
set.intersection(set1, set2 ... etc)
參數值
參數 | 描述 |
---|---|
set1 | 必需。要在其中檢索相同項目的集合。 |
set2 |
可選。其他需要在其中檢索相同項目的集合。 您可以比較任意多的集合。 集合之間由逗號分隔。 |
更多實例
實例
對比 3 個集合,并返回存在于所有 3 個集合中的項目:
x = {"a", "b", "c"} y = {"c", "d", "e"} z = {"f", "g", "c"} result = x.intersection(y, z) print(result)