在Python中集合set是基本数据类型的一种,它有可变集合(set)和不可变集合(frozenset)两种。创建集合set、集合set添加、集合删除、交集、并集、差集的操作都是非常实用的方法。
集合是可哈希的无序、可变类型,不能作为字典的键,但可以作为值使用。
创建集合
方法1: set1 = {'a','b','c'} print(type(set1)) # ---> <class 'set'> 方法2: list1 = ['a','b','c','d'] str1 = 'python' dict1 = {'name':'sunwk','age':1000,} tup1 = ('Google', 'Runoob', 1997, 2000) print('list1:',set(list1)) # --> list1: {'c', 'd', 'a', 'b'} print('str1:',set(str1)) # --> str1: {'o', 'y', 'h', 't', 'n', 'p'} print('dict1:',set(dict1)) # --> dict1: {'age', 'name'} print('tup1',set(tup1)) # --> tup1 {2000, 'Google', 1997, 'Runoob'} 实例1: list1 = [[1,2],3,4] print('list1:',set(list1)) # --> TypeError: unhashable type: 'list' ''' 小结: 1、集合的创建使用set来创建或者直接使用{}括起来,和字典有些路类似,只不过结合没有键值对 2、可以把列表、字符串、字典、元组变成集合类型,总结起来就是可以把可迭代的数据类型变成结合。 3、int型是不可迭代类型,所以set(int)是不可以的。 4、set(dict)时,把字典中的键作为元素创建成结合 5、集合中每个元素必须都是不可变类型 '''
特殊应用
list1 = ['a','b','c','a'] str1 = 'array' print('list1:',set(list1)) # --> list1: {'a', 'b', 'c'} print('str1:',set(str1)) # --> str1: {'a', 'r', 'y'} ''' 集合可以去除字符串、列表、字典、元组中重复的元素。 '''
集合增加元素
set.add()
d = {1,2,'lvcm','zhangjm'} d.add("sunwk") print('d -->',d) # d --> {'zhangjm', 'lvcm', 2, 'sunwk', 1}
set.update()
f = {1,2,'lvcm'} f.update('abc') print(f) # {1, 2, 'a', 'lvcm', 'c', 'b'} f.update([12,'suwk']) print(f) # {'lvcm', 1, 2, 'suwk', 12}
小结:
- 使用add增加数据,会把添加的数据拆分成N个元素添加到原有集合中
- 使用update增加数据,会把添加的数据看成一个元素添加到原有集合中