码迷,mamicode.com
首页 > 其他好文 > 详细

素数、杨辉三角、封装结构和集合操作(16)——集合及操作

时间:2019-11-04 18:04:49      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:c11   杨辉三角   tab   ict   call   argument   recent   script   table   

集set

可变的、无序的、不重复的元素的集合

set定义

s1=set()    ##定义空set
type(s1)
set

s2={}    ##不是set而是字典
type(s2)
dict

s3={1,2,3}    ##非空set可以用此写法定义
type(s3)
set

s4={a:1,b:2}    ##字典需要键对定义
type(s4)
dict

s5=set(range(5))
s5
{0, 1, 2, 3, 4}

s6={abc,2,3,3,abc,(1,2,3),(2,3),(2,3)}    ##set元素无法重复,set是比较元素的hash值
s6
{(1, 2, 3), (2, 3), 2, 3, abc}

s6[1:]    ##set是无序集合,没有索引概念,无法支持索引切片
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-c11924d6da50> in <module>
----> 1 s6[1:]

TypeError: set object is not subscriptable

list(s6)
[2, 3, abc, (1, 2, 3), (2, 3)]
list(s6)[1:]    ##可以以列表方式切片
[3, abc, (1, 2, 3), (2, 3)]

s7={1,abc,(1,2),[],(1,[2,3]),None,True}    ##set不支持不可hash类型或嵌套不可hash类型的元素,大部分可变序列都为不可hash类型
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-52-15199fdfbfbe> in <module>
----> 1 s7={1,abc,(1,2),[],(1,[2,3]),None,True}

TypeError: unhashable type: list

hash([],bytearray(),{},{1})
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-5a006b60c685> in <module>
----> 1 hash([],bytearray(),{},{1})

TypeError: hash() takes exactly one argument (4 given)

set的元素

set的元素要求必须可以hash

元素不可以使用索引

set可以迭代

 

素数、杨辉三角、封装结构和集合操作(16)——集合及操作

标签:c11   杨辉三角   tab   ict   call   argument   recent   script   table   

原文地址:https://www.cnblogs.com/omgasw/p/11792870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!