溫馨提示×

python set運算如何實現集合的并集

小樊
108
2024-08-27 11:02:02
欄目: 編程語言

在Python中,可以使用set類型來表示集合。要計算兩個集合的并集,可以使用union()方法或者"|"操作符。

下面是一個例子:

# 定義兩個集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 使用union()方法計算并集
union_set = set1.union(set2)
print("使用union()方法計算并集:", union_set)

# 使用"|"操作符計算并集
union_set = set1 | set2
print("使用'|'操作符計算并集:", union_set)

輸出結果:

使用union()方法計算并集: {1, 2, 3, 4, 5, 6}
使用'|'操作符計算并集: {1, 2, 3, 4, 5, 6}

這個例子中,我們定義了兩個集合set1和set2,然后使用union()方法和"|"操作符分別計算它們的并集。最后輸出的結果為{1, 2, 3, 4, 5, 6}。

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