首页 > 代码库 > Python-数据结构

Python-数据结构

List

List中的内容并不一定只有一种类型,一个List中可能既有number,又有string,还可能有子List

List用[]表示

List的基本方法有:append,sort等

要从一个List中删除某元素,可以使用del函数(它不是List的方法)

#!/usr/bin/pythonmylist = [apple,pear,banana]print mylist is,mylistmylist.sort()print after sort, mylist is,mylistfirst = mylist[0]del(mylist[0])print have bought,first,, now remains,for item in mylist:    print item,

output:

mylist is [‘apple‘, ‘pear‘, ‘banana‘]
after sort, mylist is [‘apple‘, ‘banana‘, ‘pear‘]
have bought apple , now remains banana pear

 

Tuple

里面的元素不可更改,tuple中可以有子tuple

Tuple用()表示

空Tuple用()表示

只含一个元素的Tuple要在该元素后面加上[,]  e.g.  one_elem_tuple = (2,)

#!/usr/bin/pythonold_zoo = (tiger,lion,elephant)print All animals in the old_zoo are,old_zooprint Number of animals in the old_zoo is,len(old_zoo)new_zoo = (monkey,panda,old_zoo)print All animals in the new_zoo are,new_zooprint Number of animals in the new_zoo is,len(new_zoo)-1+len(new_zoo[2])print Animals bought from the old_zoo are,new_zoo[2]print The last animal bought from the old_zoo is,new_zoo[2][2]

output:

All animals in the old_zoo are (‘tiger‘, ‘lion‘, ‘elephant‘)
Number of animals in the old_zoo is 3
All animals in the new_zoo are (‘monkey‘, ‘panda‘, (‘tiger‘, ‘lion‘, ‘elephant‘))
Number of animals in the new_zoo is 5
Animals bought from the old_zoo are (‘tiger‘, ‘lion‘, ‘elephant‘)
The last animal bought from the old_zoo is elephant

 

Dictionary

键值对

key必须唯一

key只能用【不可改变】的对象(e.g. string),value可以用【不可改变或者可改变】的对象

d={key1:value1,key2:value2,...}

帮助手册:help(dict)

#!/usr/bin/pythonab = {John:John@163.com,      Bill:Bill@qq.com,      Lily:Lily@sohu.com}print John\‘s address is,ab[John]del ab[Bill]print After del, there are {0} contacts in the address-book.format(len(ab))for name,address in ab.items():    print name,addressab[Rose]=Rose@sina.comif Rose in ab: #OR ab.has_key(‘Rose‘)    print Rose\‘s address is,ab[Rose]

output:

John‘s address is John@163.com
After del, there are 2 contacts in the address-book
John John@163.com
Lily Lily@sohu.com
Rose‘s address is Rose@sina.com

items方法返回一个由tuple组成的list,每个tuple包含两个元素:key和value

 

序列:list,tuple,string

主要特点:成员测试(【是否属于该序列】的表达式),下标操作

切片

eg. a[1:4] 取1至3
a[1:] 从1取到结尾
a[:4] 从开头到3
a[::2] 从开头到结尾,每2步一取

a[::-1] 从尾到头倒过来取
a[4:1:-1] 从4到2倒过来取
a[-1] 取最后一个字符

 

Set

>>> bri = set([‘brazil‘,‘russia‘,‘india‘])
>>> ‘india‘ in bri
True
>>> ‘usa‘ in bri
False
>>> bric = bri.copy()
>>> bric.add(‘china‘)
>>> bric.issuperset(bri)
True
>>> bri.remove(‘russia‘)
>>> bri & bric
set([‘brazil‘, ‘india‘])

 

当创建一个对象并将它赋值给一个变量时,变量名指向存放对象的内存。

e.g.

shoplist = [‘apple‘,‘mango‘,‘carrot‘,‘banana‘]

mylist = shoplist   #shoplist和mylist指向同一内存。

del shoplist[0]  #此时shoplist和mylist都少了第一个元素,因为他们指向的是同一内存。

mylist = shoplist[:]

del shoplist[0]  #此时shoplist少了第一个元素,而mylist不变

以上规则对序列或复杂对象适用,对简单对象不适用(e.g. 整数)。

实际上,对于a=4;b=a;a=5来说,a指向了一个新的内存,而b还是指向原先的内存,因此b的值不变。只有改变了共同的内存,才会同时改变两个变量。

 

String

所有的string类型数据都是class str的对象,查看该类的更多方法,使用help(str)

Python-数据结构