标签:Set集合
一、set集合:一组无序的且不重复(自动消除重复)的数据集合
演示:
list01 = [11, 22, 33, 44, 55, 22, 66, 77]
print(list01[0])
list01.append(88)
print(list01)
set01 = {11, 22, 33, 44, 55, 66, 77}
# set存储数据的时候是无序的,初始化的顺序和打印出来的顺序是不一样的
# set集合在存储的时候回消除重复值
# print(set01[0]) 会报错
print(set01)
set02 = {"Steven", "Abby", "Alice", "Steven"}
print(set02)
执行结果:
C:\python\python.exe C:/python/demo/file3.py
11
[11, 22, 33, 44, 55, 22, 66, 77, 88]
{33, 66, 11, 44, 77, 22, 55}
{'Alice', 'Steven', 'Abby'}
Process finished with exit code 0
二、set和list区别
set在存储的时候,先把元素转为哈希值,哈希值是按顺序存储的。
# 1.创建时直接初始化
set01 = {11, 22, 33, 44, 55, 66, 77}
# 输出
print(set01)
# 2.创建空的set集合,然后往里面加入值
set02 = set()
print(type(set02))
set02.add("Steven")
set02.add("Abby")
set02.add("Alice")
print(set02)
# 3.遍历,顺序是按照转换为哈希值后的顺序排序的
for i in set01:
print(i, end=" ")
执行结果:
C:\python\python.exe C:/python/demo/file3.py
11
[11, 22, 33, 44, 55, 22, 66, 77, 88]
{33, 66, 11, 44, 77, 22, 55}
{'Abby', 'Steven', 'Alice'}
{33, 66, 11, 44, 77, 22, 55}
<class 'set'>
{'Abby', 'Steven', 'Alice'}
33 66 11 44 77 22 55
Process finished with exit code 0
标签:Set集合
原文地址:http://blog.51cto.com/13043937/2115096