Python基础学习笔记5 tuple,set

来源:互联网 发布:pdf阅读器软件下载 编辑:程序博客网 时间:2024/06/07 21:08

1. tuple是一种序列类型的数据,和list,str很类似,它的特点是其中的元素不能更改,元素可以是任何类型(list类似)

2. tuple和list的相互转化:分别用list(), tuple()就可以相互转换

listA = ['I','am','learning','python']testTuple = tuple(listA)print testTuple

返回:('I', 'am', 'learning', 'python')
3.tuple通常用在定义常量,对数据进行写保护,因此它的操作效率比list要高
4.set: 非序列类型的数据,不可以重复
set的定义方法之一:
s1 = set("aabbcc")print s1
返回set(['a', 'c', 'b'])
但是不能创建含有list/dict的set,set的赋值或者说原地修改和list 不一样,不能通过索引去删除,可以通过set.add()方法:
s1.add("c")print s1
返回set(['a', 'c', 'b']) 因为c已经存在,所以被屏蔽掉了
方法之二:
s1 = {'hello','Python'}print type(s1)
返回<type 'set'>
help(set)可以查看所有set的方法:e.g s1.pop()删除并且返回该元素,s1.update(s2),合并两个set
有意思的小区别:s1.remove() s1.discard()都是删掉元素,但是discard如果元素不存在,do nothing,而remove就会报错:raise a keyError
set的强大之处在于对集合的处理,
求s1是否是s2的子集:
s2 = {'hello','Python', 'I','like','it'}print s1.issubset(s2)
返回:True
求并集:s1 union s2  (或者 s1 | s2)
求交集:
print s1.intersection((s2))
返回set(['Python', 'hello'])
更多方法在需要用到的时候可以用help(set)去查询,thanks God


0 0