溫馨提示×

Set在Python能做集合運算嗎

小樊
88
2024-08-02 22:46:12
欄目: 編程語言

是的,Set在Python中可以進行集合運算??梢允褂靡韵鲁R姷募线\算:

  • 并集:使用union()方法或|運算符
  • 交集:使用intersection()方法或&運算符
  • 差集:使用difference()方法或-運算符
  • 對稱差集:使用symmetric_difference()方法或^運算符

例如:

set1 = {1, 2, 3}
set2 = {2, 3, 4}

# 并集
union_set = set1.union(set2)
print(union_set)  # 輸出 {1, 2, 3, 4}

# 交集
intersection_set = set1.intersection(set2)
print(intersection_set)  # 輸出 {2, 3}

# 差集
difference_set = set1.difference(set2)
print(difference_set)  # 輸出 {1}

# 對稱差集
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # 輸出 {1, 4}

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女