集合
1.集合元素之间无序,每个元素唯一,不存在相同元素 2.集合元素不可更改,不能是可变数据类型 集合用{}表示,元素间用,分隔 建立集合类型用{}或者set() .建立空集合类型,必须用set(),因为空的{}是默认生成字典类型的
>>> s = {'a','b',123} >>> t = set('abab123') >>> s|t {'b', '3', 'a', '1', '2', 123} >>> t {'b', '3', '1', '2', 'a'} >>> s-t {123} >>> t-s {'2', '3', '1'} >>> s&t {'b', 'a'} >>> s^t {'1', '2', 123, '3'} >>> s<=t False >>> s>t False >>>
>>> s = {'a','b',123} >>> s.add('c') >>> s {123, 'c', 'b', 'a'} >>> s.discard('d')#删除一个元素,不存在也不会报错 >>> s {123, 'c', 'b', 'a'} >>> s.remove('d') Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> s.remove('d') KeyError: 'd' >>> s.clear() >>> s set() >>> p = s.pop() Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> p = s.pop() KeyError: 'pop from an empty set' >>> s = set('sdvfb') >>> p =s.pop() #随机返回a的一个元素,更新a(从a中删除该元素),若a为空产 KeyError异常 >>> p 'b' >>> s {'v', 's', 'f', 'd'}
>>> p = s.copy() >>> p {'d', 'f', 's', 'v'} >>> len(s) 4 >>> 'd' in s True >>> 'd'not in s False >>> set(cd) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> set(cd) NameError: name 'cd' is not defined >>> set('sf')# set(x) :将其它类型变量x转化为集合类型 {'s', 'f'}
>>> a = {'p','y',123} >>> for i in a: print(i,end='') p123y
#数据去重 >>> ls =['l','l','s','s',123] >>> ls ['l', 'l', 's', 's', 123] >>> s =set(ls) >>> s {'l', 123, 's'} >>> lt = list(s) >>> lt ['l', 123, 's']
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)
{0, 1, 2, 3, 4, 5}#{}的形式