設置 intersection() 方法
intersection() 方法用於獲取在給定集合中共有/存在的所有元素的列表。
用法:
set1.intersection(set1, set2, set3, ...)
參數:
set1
– 表示要與該集合進行比較的集合。set2, set3, ...
– 這些是可選的集合,我們可以提供多個集合進行比較。
返回值:
這個方法的返回類型是<class 'set'>
,它返回存在於所有集合中的元素的集合。
範例1:
# Python Set intersection() Method with Example
# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}
# intersection() method call
x = cars_1.intersection(cars_2)
# printing the sets
print("cars_1:", cars_1)
print("cars_2:", cars_2)
print("x:", x)
輸出
cars_1:{'Porsche', 'Audi', 'Lexus'} cars_2:{'Porsche', 'Lincoln', 'Mazda'} x:{'Porsche'}
範例2:
# Python Set intersection() Method with Example
# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}
# printing the results
print("x:", x)
print("y:", y)
print("z:", z)
# printing the common elements
print("x.intersection(y,z):", x.intersection(y,z))
print("y.intersection(x,z):", y.intersection(x,z))
print("x.intersection(z,y):", x.intersection(z,y))
print("y.intersection(z,x):", y.intersection(z,x))
print("z.intersection(x,y):", z.intersection(x,y))
輸出
x:{'PQR', 'ABC', 'XYZ'} y:{'PQR', 'ABC', 'XYZ'} z:{'DEF', 'ABC', 'MNO'} x.intersection(y,z): {'ABC'} y.intersection(x,z): {'ABC'} x.intersection(z,y): {'ABC'} y.intersection(z,x): {'ABC'} z.intersection(x,y): {'ABC'}
相關用法
- Python Set intersection_update()用法及代碼示例
- Python Set issuperset()用法及代碼示例
- Python Set issubset()用法及代碼示例
- Python Set isdisjoint()用法及代碼示例
- Python Set difference_update()用法及代碼示例
- Python Set union()用法及代碼示例
- Python Set pop()用法及代碼示例
- Python Set add()用法及代碼示例
- Python Set clear()用法及代碼示例
- Python Set update()用法及代碼示例
- Python Set symmetric_difference()用法及代碼示例
- Python Set symmetric_difference_update()用法及代碼示例
- Python Set discard()用法及代碼示例
- Python Set copy()用法及代碼示例
- Python Set difference()用法及代碼示例
- Python Set remove()用法及代碼示例
- Python Pandas Series.cummin()用法及代碼示例
- Python Pandas Series.cov()用法及代碼示例
- Python Pandas Series.astype()用法及代碼示例
- Python Pandas Series.mad()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Set intersection() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。