- 集合是不重复、无序的,可以用{ }或者set来表示
- { }有两种意思:字典和集合
- 里面是键值对,则为字典;若为单个的值,则为集合
1.定义集合
name = {'hello','good',1}
print(name)
2.添加元素
name = {'hello','good',1}
name.add('呵呵')
print(name)
name.clear()
print(name)
注意:空集合:set{ } ; 空字典:{ }
3.删除元素:pop()、remove()、discard()
name = {'hello','good',1}
name.pop()
print(name)
name.remove('good')
print(name)
name.discard('good')
print(name)
4.拼接集合:union()、update()
- union():将多个集合合并生成一个新的集合
- update():A.update(B) 将B拼接到A里,B可以是集合、列表、元组等
name = {'hello','good',1}
name.union({'aa','bb'})
print(name)
name.update(['hhh','ccc'])
print(name)
5.set支持的一些算术运算符
- 减:差集:A-(A∩B)
- & :交集
- | :并集
^ : 差集的并集(即除了交集之外的元素)
first = {'孟浩然','李白','李清照','苏轼'}
second = {'王安石','李白','李商隐','岑参'}
third = {'刘禹锡','李白','李清照','王维'}
print(first-second)
print(first & second)
print(first | second)
print(first ^ second)
6.集合小练习
nums = {2,4,6,1,8,7,9,6,3,5,,2,1,9}
x = set(nums)
print(x)
y = list(x)
y.sort(reverse = True)
nums = {2,4,6,1,8,7,9,6,3,5,,2,1,9}
x = tuple(nums)
print(x)
y = set(x)
print(y)
z = list({'name':'sxl','age':25})
print(z)
|