python中常用的内建数据结构

来源:互联网 发布:淘宝卖衣服需要什么证 编辑:程序博客网 时间:2024/06/03 13:34

1、列表(list)

可以参考这里:http://www.runoob.com/python/python-lists.html

list就像C++里面的vector一样。。。如果vector用熟了,list应该也似曾相识。记住list是可变的,也就是说我们可以去直接修改它。

示例代码:

#coding=utf-8print "this is an example of LIST!\n"list=['apple','bread','milk','coffee']#创建列表print "the list is:",list[0:]#从第0个元素开始截取列表print "the first item is:",list[0]#访问列表元素print "the last but one:",list[-2]#截取倒数第二个元素print "let's print list[0:3):",list[0:3]#用范围来访问列表元素print "I want a pear, add a pear to our list!\n"list.append('pear')#添加元素print "now show it:",list[0:]print "now let's sort it"list.sort()#排序print "the result is:",list[0:]print "delete milk!"del list[3]#删除print list[0:]print "the length is:",len(list)#获取长度print "now let's count how many apples are there in the list:",list.count("apple")#统计元素个数print "get the index of coffee:",list.index("coffee")#获取元素下标print "now remove coffee\n"list.remove("coffee")#通过remove删除元素print list[0:]print "now reverse the list\n"list.reverse()#反转列表print list[0:]
运行效果:

(没有用python的ide,是在powershell下编译运行的。。虽然丑但是凑合着也能看=。=)


2、元组(tuple)

OMG。。。python所谓的“元组”长得和lisp的“列表”一模一样=。=(好吧这并没有什么意义,只是想吐槽一下=。=)

元组和列表唯一的区别在于元组是不可变的,也就是说一旦创建你就不能直接修改它,这就导致了元组没有append方法(因为不能修改,添加元素就没有意义了),也没有remove(删除某个元素)。但是tuple的删除可以用del方法,这会删去整个元组。当然,要修改元组也可以通过另一种方式:

tup1=("LiMing",18,'m')tup2=("HanMeimei",18,'f')list1=list(tup1)#change the tuple into a list#now set the original value 'm' to be 'f'list1[2]='f'tup1=tuple(list1)print tup1[0:]
通过list()方法和tuple()方法可以实现列表、元组之间的相互转换

3、字典(dictionary)

字典就是python中的哈希表,它的特点是:

1)字典和数学上的集合一样,是无序的

2)键值必须唯一,如果出现重复会取后一个

3)键值必须不可变(也就是说可变的东西,比如列表,不可以充当键值)

示例代码:

#coding=utf-8dict={"name":"john","age":18,"sex":'m',"job":"salesman","location":"hangzhou"}if(dict.has_key("salary")): #检查键值是否存在,如果存在输出yes    print "yes"else:    print "no"val=dict.get("name","no such person")#获取键值对应的值,如果不存在返回第二个参数print "the name is: %s"%vallist=dict.keys()#以列表返回所有的键print "the according list is:",list[0:]items=dict.items()#返回一个列表,元素是键值对print "the result is",items[0:]values=dict.values()#以列表形式返回所有的值print "the value is",values[0:]deleted=dict.pop("age")#删除键值对,并返回这个值print "after deleting the pair:",dictprint deleted#会打印18'''注意:还有一种和pop类似的方法,叫做popitem,例如:item=dict.popitem()它会随机删除字典中的键值对,并返回这个值'''newdict={"salary":9000,"car brand":"volkswegen"}dict.update(newdict)#把newdict的键值对增添到dict中print "now the dict is",dictkeytuple=("name","age","sex")dict2=dict.fromkeys(keytuple,"unknown")#拷贝给定的键,默认值是第二个参数print "the new dict is",dict2
运行效果(这次用PyCharm了。。):



小结:列表、元组和字典都是“序列”,序列的基本特点是将元素和位置(也可以是“键值”)关联了起来,从而方便我们的访问。


4、集合(set)

可以用数学上学的集合来理解,也就是说它是无序的、互异的。(确定性可能不怎么体现得出来=。=)

python中的集合没有特殊的表达方式(不像列表用[],元组用(),字典用{}),而是通过函数set()来获取,例如:

list2=[1,1,1,3453,64,1231,0]myset2=set(list2)print "the set is",myset2
得到的结果是:

the set is set([64, 1, 3453, 0, 1231])


原创粉丝点击