Python set union()方法可以合并两个集合。它可以将两个集合中的所有元素合并到一个新的集合中,并返回结果集合。
使用方法
#定义两个集合 set1 = {'Apple', 'Banana', 'Cherry'} set2 = {'Orange', 'Mango', 'Banana'} #使用union()方法合并集合 set3 = set1.union(set2) #输出结果集合 print(set3)
输出结果:{'Banana', 'Apple', 'Orange', 'Cherry', 'Mango'}
可以看到,结果集合中包含了两个集合中的所有元素,并且没有重复元素。
除了union()方法,Python还提供了其他的方法来合并集合,如update()方法、intersection()方法和difference()方法等。
update()方法
#定义两个集合 set1 = {'Apple', 'Banana', 'Cherry'} set2 = {'Orange', 'Mango', 'Banana'} #使用update()方法合并集合 set1.update(set2) #输出结果集合 print(set1)
输出结果:{'Banana', 'Apple', 'Orange', 'Cherry', 'Mango'}
可以看到,使用update()方法合并的结果集合和使用union()方法合并的结果集合是一样的。这是因为update()方法会将两个集合中的所有元素添加到第一个集合中,并返回结果集合。
intersection()方法
#定义两个集合 set1 = {'Apple', 'Banana', 'Cherry'} set2 = {'Orange', 'Mango', 'Banana'} #使用intersection()方法合并集合 set3 = set1.intersection(set2) #输出结果集合 print(set3)
输出结果:{'Banana'}
可以看到,使用intersection()方法合并的结果集合只包含了两个集合中共同存在的元素,即Banana。
difference()方法
#定义两个集合 set1 = {'Apple', 'Banana', 'Cherry'} set2 = {'Orange', 'Mango', 'Banana'} #使用difference()方法合并集合 set3 = set1.difference(set2) #输出结果集合 print(set3)
输出结果:{'Apple', 'Cherry'}
可以看到,使用difference()方法合并的结果集合只包含了第一个集合中存在而第二个集合中不存在的元素,即Apple和Cherry。
来说,Python set union()方法可以将两个集合中的所有元素合并到一个新的集合中,并返回结果集合;update()方法会将两个集合中的所有元素添加到第一个集合中,并返回结果集合;intersection()方法会将两个集合中共同存在的元素合并到一个新的集合中,并返回结果集合;difference()方法会将第一个集合中存在而第二个集合中不存在的元素合并到一个新的集合中,并返回结果集合。