union函数:
union() 方法返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。
语法:
set.union(set1, set2…)
例子1:
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.union(y)
print(z)
输出结果:
{‘cherry’, ‘runoob’, ‘google’, ‘banana’, ‘apple’}
例子2:
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
result = x.union(y, z)
print(result)
{‘c’, ‘d’, ‘f’, ‘e’, ‘b’, ‘a’}
额外知识补充:
set2也可以是列表
set1 = {'小苹果','大桃子','长香蕉'}
set4=['小可爱','西红柿']
set1.union(set4)
{‘大桃子’, ‘小可爱’, ‘小苹果’, ‘西红柿’, ‘长香蕉’}