温馨提示×

python中set如何进行交集运算

小樊
112
2024-12-10 00:51:26
栏目: 编程语言

在Python中,可以使用&运算符或intersection()方法对两个集合进行交集运算。

例如:

set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} # 使用 & 运算符进行交集运算 intersection = set1 & set2 print(intersection) # 输出:{4, 5} # 使用 intersection() 方法进行交集运算 intersection = set1.intersection(set2) print(intersection) # 输出:{4, 5} 

以上代码中,set1set2是待进行交集运算的两个集合,intersection是运算结果。

0