python union()方法,返回并集set

union()方法

union()是python集合set内置的方法,可用于返回调用对象集合与多个集合或多个其它可迭代对象iterable的元素并集,因为集合的去重功能,毕竟中的相同的元素将被去重,只保留一个。


union()语法及参数结构

set1.union( iterable1[, iterable2...iterableN] )

参数解析表:

参数描述
iterable1必须参数,为python可迭代对象,如集合set、列表list、元组tuple等等
iterable2...IterableN可选参数,性质同上

union()返回值

返回调用对象与参数的并集,并去重后的新的python集合set,union()方法并不修改原集合。


union()方法实例代码

>>> set1 = {2,5,8}
>>> set2 = {1,3,6}
>>> set3 = {7,6,9}
>>> set1.union(set2,set3) #参数为集合set
{1, 2, 3, 5, 6, 7, 8, 9} #union()返回的集合进行了去重
>>> set1
{8, 2, 5}
>>> list1 = ['a','b'] 
>>> list2 = ['c','d']
>>> set1.union(list1,list2) #参数为列表list
{'d', 2, 5, 8, 'b', 'c', 'a'}
>>> tuple1 = ('笨鸟工具','x1y1z1.com')
>>> tuple2 = ('python','全栈')
>>> set1.union(tuple1,tuple2) #参数为元组tuple
{2, '全栈', 5, 8, 'python', 'x1y1z1.com', '笨鸟工具'}

实例代码提示

如上代码,分别为python的union()方法传递了三种类型的参数,分别是集合set、列表list、元组tuple,这三种参数都是iterable可迭代对象,大家也可以试试其它的可迭代对象,比如字典dict、字符串str、range类型等等。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.