python基础学习——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
来源:互联网 发布:知君本无邪by尼罗鲤鱼 编辑:程序博客网 时间:2024/04/29 17:50
python 是个很方便的数据处理工具,搞搜索的很多都用此语言。优点是简单易用,功能强大。一个复杂的功能就只需要几行代码搞定。
快速开发,对性能稳定性要求不高,用它再合适不过了。
先系统的学习下。
一)内容介绍
python的基础数据结构有:列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set)
1)列表(list)
#1)创建list = ['1',(1,2),'1', '2']#2) 得到list 长度>>> print len(list)4#3) 删除>>> del list[0]>>> print list[(1, 2), '1', '2']>>> del list[0:2]>>> print list['2']#4) 添加>>> list.append('3')>>> print list['2', '3']#5) 插入>>> list[0:0] = ['sample value']>>> print list['sample value', '2', '3']>>> list[0:0] = ['sample value', 'sample value 1']>>> print list['sample value', 'sample value 1', 'sample value', '2', '3']>>> list[1:2] = ['sample value 2', 'sample value 3']>>> print list['sample value', 'sample value 2', 'sample value 3', 'sample value', '2', '3']#6) 取值,遍历取值单个值>>> print list[0]sample value>>> print list[1]sample value 2>>> print list[2]sample value 3取片段>>> print list[2:4]['sample value 3', 'sample value']遍历>>> for line in list:... print line... sample valuesample value 2sample value 3sample value23list的方法L.append(var) #追加元素L.insert(index,var)L.pop(var) #返回最后一个元素,并从list中删除之L.remove(var) #删除第一次出现的该元素L.count(var) #该元素在列表中出现的个数L.index(var) #该元素的位置,无则抛异常 L.extend(list) #追加list,即合并list到L上L.sort() #排序L.reverse() #倒序2)元祖(tuple)
#元组和列表十分类似,只不过元组和字符串一样是
#不可变的 即你不能修改元组
tuple = ('a', 'b', 'c', 'd', 'e')>>> print tuple[0]a>>> print tuple[0:2]('a', 'b')3)字符串(string)
string = "Hello My friend">>> print string[0]H>>> print string[0:5]Hello字符串包含判断操作符:in,not in>>> print 'He' in stringTrue>>> print 'sHe' in stringFalse*后面跟数字表示字符串重复的次数,比如 print 'hello'*5>>> hellohellohellohellohello string模块,还提供了很多方法,如S.find(substring, [start [,end]]) #可指范围查找子串,返回索引值,否则返回-1S.rfind(substring,[start [,end]]) #反向查找S.index(substring,[start [,end]]) #同find,只是找不到产生ValueError异常S.rindex(substring,[start [,end]])#同上反向查找S.count(substring,[start [,end]]) #返回找到子串的个数S.lowercase()S.capitalize() #首字母大写S.lower() #转小写S.upper() #转大写S.swapcase() #大小写互换S.split(str, ' ') #将string转list,以空格切分S.join(list, ' ') #将list转string,以空格连接处理字符串的内置函数len(str) #串长度cmp("my friend", str) #字符串比较。第一个大,返回1max('abcxyz') #寻找字符串中最大的字符min('abcxyz') #寻找字符串中最小的字符string的转换 float(str) #变成浮点数,float("1e-1") 结果为0.1int(str) #变成整型, int("12") 结果为12int(str,base) #变成base进制整型数,int("11",2) 结果为2long(str) #变成长整型,long(str,base) #变成base进制长整型,字符串的格式化(注意其转义字符,大多如C语言的,略)str_format % (参数列表) #参数列表是以tuple的形式定义的,即不可运行中改变>>>print ""%s's height is %dcm" % ("My brother", 180)#结果显示为 My brother's height is 180cm4)字典(dict)
key-value的数据结构,跟c++中的stl:map类似。
#创建字典:#1)基本d = {} #空字典d = {'name':'tom', 'age':22} #等价d = {}d['name'] = 'tom'd['age'] = 222)dictd = dict() #空d = dict(name='tom', age=22)d = dict([('name','tom'), ('age',22)]) #等价keys = ['name','age']values = ['tom', 22]d = dict(zip(keys,values))#3) fromkeys>>> dict.fromkeys(['name','age'],'default_value'){'age': 'default_value', 'name': 'default_value'}#判断key是否存在if k in d: #k not in dosomething()#读取print d['name'] #存在得到结果,但是若键不存在,将引发异常KeyError。慎用,建议不使用print d.get('name', 'jack') #存在得到,若键不存在,返回第二个参数default_value.若是没有设default_value返回None #使用用例if k in d: print d[k]try: print d[k]except KeyError: dosomething()print d.get(k, default)#等价 d[k] if k in d else default#遍历for key in d: print key, d[key] #等价 for key in d.keys()for key,value in d.items(): print key, value#修改d['name'] = 'tom'd.update({'name':'tom'}) #这里支持一整组值d.update( [ ('name','tom'), ('age',2) ] ) #每个元组两个元素,(key,value)d.update('name'='tom', 'age'=4)#删除del d['key']value = d.pop('key') #删除并返回值d.clear() #清空#排序d = {'a':10, 'c':8, 'b':9, 'd':7}#1)字典排序 按照key排序keys = d.keys()keys.sort()for key in keys: print d.get(key)结果为:10987#2) 按照value进行排序sorted(d.items(), lambda x,y: cmp(x[1],y[1]))结果为:[('d', 7), ('c', 8), ('b', 9), ('a', 10)]#3) 另一种排序方法sorted(d)>>> print d{'a': 10, 'c': 8, 'b': 9, 'd': 7}#其他dictionary的方法D.get(key, 0) #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常D.has_key(key) #有该键返回TRUE,否则FALSED.keys() #返回字典键的列表D.values() #以列表的形式返回字典中的值,返回值的列表中可包含重复元素D.items() #将所有的字典项以列表方式返回,这些列表中的每一项都来自于(键,值),但是项在返回时并没有特殊的顺序 D.update(dict2) #增加合并字典D.popitem() #得到一个pair,并从字典中删除它。已空则抛异常D.clear() #清空字典,同del dictD.copy() #拷贝字典D.cmp(dict1,dict2) #比较字典,(优先级为元素个数、键大小、键值大小) #第一个大返回1,小返回-1,一样返回0 dictionary的复制dict1 = dict #别名dict2=dict.copy() #克隆,即另一个拷贝。5)集合(set)
python 的集合类型和 其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素.集合对象还支持union(联合), intersection(交), difference(差)和sysmmetricdifference(对称差集)等数学运算,和我们初中数学学的集合的非常的相似。
#创建a = [2,3,4,2,1]seta = set(a)>>> print setaset([1, 2, 3, 4]) #重复的2被删除掉了setb = set('abracadabra')setc = set('alacazam')>>> print setcset(['a', 'c', 'z', 'm', 'l'])#操作#1)in or not inx in setax not in seta#2)测试集合是否完全包含s.issubset(t) #测试是否 s 中的每一个元素都在 t 中s <= ts.issuperset(t) #测试是否 t 中的每一个元素都在 s 中s >= t#3)其他运算符s.union(t) # 合并s | ts.intersection(t) #求交s & ts.difference(t) #返回一个新的 set 包含 s 中有但是 t 中没有的元素s - ts.symmetric_difference(t) # 返回一个新的 set 包含 s 和 t 中不重复的元素s ^ ts.copy() # 返回 set “s”的一个浅复制s.update(t) s |= ts.intersection_update(t)s &= ts.difference_update(t)s -= ts.symmetric_difference_update(t)s ^= ts.add(x) #向 set “s”中增加元素 xs.remove(x) #从 set “s”中删除元素 x, 如果不存在则引发 KeyErrors.discard(x) #如果在 set “s”中存在元素 x, 则删除s.pop() #删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyErrors.clear() #删除 set “s”中的所有元素
0 0
- python基础学习——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- python基础数据结构——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- 【Python】基础学习——列表(list),元祖(tuple),字典(dict),字符串(string),集合(set)
- 列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 的基本方法
- python 列表list 元组tuple 字典dict 集合set 介绍
- python 列表list 元组tuple 字典dict 集合set 介绍
- Python学习笔记(9)-列表list、元组tuple、字典dict、集合set
- Python学习笔记(四)—列表(list)、元组(tuple)和字典(dictionary)、集合(set)
- python之列表(list),元组(tuple),集合(set),字典(dict)
- python的列表(List),元组(Tuple),集合(Set),字典(Dict)
- Python中的列表(list),元组(Tuple),字典(Dict)和集合(Set)
- Python中的列表(list),元组(tuple),集合(set),字典(dict)
- python中str(字符串)、list(列表)、tuple(元组)、dict(字典)相互转化关系及字典键-值遍历
- Python学习笔记---元组(tuple)、列表(list)、字典(dict)
- 元组(tuple)、列表(list)、集合(set)和字典(dict)理解
- list和tuple:列表和元组,dict和set字典和集合
- python学习-------list、tuple、set、dict
- Python列表(list)、字典(dict)、字符串(string)基本操作小结
- 内存、主存和高速缓存
- 安卓Application.mk文件的属性说明和基本写法
- js数组
- C语言运算符优先级列表(超详细)
- iOS 9界面适配利器:详解Xcode 7的新特性UIStackView
- python基础学习——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- How can I send an email by Java application?
- 二级指针与二维数组
- WPF编程学习——窗口
- eclipse集成tomcat,完成一个web实例
- 塔防TDTK 敌人移动到目标转向
- Windows平台下搭建Obcject-C平台
- linux ln 命令使用参数详解(ln -s 软链接)
- slice,splice,substr和substring的区别