python set运算如何实现集合的交集
导读:在Python中,可以使用set( 函数或者集合对象的intersection( 方法来计算两个集合的交集。 以下是使用set( 函数的示例: # 定义两个集合 set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6}...
在Python中,可以使用set()函数或者集合对象的intersection()方法来计算两个集合的交集。
以下是使用set()函数的示例:
# 定义两个集合
set1 = {
1, 2, 3, 4}
set2 = {
3, 4, 5, 6}
# 计算交集
intersection_set = set1 &
set2
print(intersection_set) # 输出: {
3, 4}
以下是使用intersection()方法的示例:
# 定义两个集合
set1 = {
1, 2, 3, 4}
set2 = {
3, 4, 5, 6}
# 计算交集
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {
3, 4}
还可以使用intersection()方法同时计算多个集合的交集:
# 定义三个集合
set1 = {
1, 2, 3, 4}
set2 = {
3, 4, 5, 6}
set3 = {
3, 4, 7, 8}
# 计算交集
intersection_set = set1.intersection(set2, set3)
print(intersection_set) # 输出: {
3, 4}
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: python set运算如何实现集合的交集
本文地址: https://pptw.com/jishu/696257.html
