---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-dc6136f08449> in <module>()
1 x = frozenset(range(5))
----> 2 x.add(1)
AttributeError: 'frozenset' object has no attribute 'add'
集合应用案例
import random
import time
#集合和字典的操作在比较上很高效
x1 = list(range(10000))
x2 = tuple(range(10000))
x3 = set(range(10000))
x4 = dict(zip(range(10000),range(10000)))
r = random.randint(0,9999)
for t in (x4, x3, x2, x1):
start = time.time()
for i in range(9999999):
r in t
print(type(t),"time used:",time.time() - start)
<class 'dict'> time used: 1.1369783878326416
<class 'set'> time used: 1.1725521087646484
<class 'tuple'> time used: 827.3122997283936
<class 'list'> time used: 847.166533946991
import random
# random.choice从序列中获取一个随机元素。
num = set([random.choice(range(1000)) for i in range(100)])
print("len of num:",len(num))
len of num: 99
import random
#指定分布中选取不重复元素
random.sample(range(10000), 20)
# 指定list是否有非法元素,转换为set更高效import random
lstColor = ('red', 'green', 'blue')
colors = [random.choice(lstColor) for i in range(10000)]
if(set(colors) - set(lstColor)):
print("error")