Python学习日志(五)之数据结构

来源:互联网 发布:攻破网站数据库 编辑:程序博客网 时间:2024/05/18 13:10

第9章 数据结构
1.列表
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,你在每个项目之间用逗号分割。

列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加(append)或删除(del)项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。

#!/usr/bin/python# Filename: using_list.py# This is my shopping listshoplist = ['apple', 'mango', 'carrot', 'banana']print 'I have', len(shoplist),'items to purchase.'print 'These items are:', # Notice the comma at end of the linefor item in shoplist:    print item,print '\nI also have to buy rice.'shoplist.append('rice')print 'My shopping list is now', shoplistprint 'I will sort my list now'shoplist.sort()print 'Sorted shopping list is', shoplistprint 'The first item I will buy is', shoplist[0]olditem = shoplist[0]del shoplist[0]print 'I bought the', olditemprint 'My shopping list is now', shoplist

上述代码中强调的print后的逗号,貌似因为版本的不同,并不奏效。后面需要再查一下。

2.元组
元组和列表类似,但是元组和字符串一样,是不可变的。即你不能修改元组。
列表用方括号定义,元组通过圆括号定义。

3.字典
字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的。
键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

4.序列
序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。【切片时和MATLAB相似】

5.参考
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
例:

#!/usr/bin/python# Filename: reference.pyprint 'Simple Assignment'shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist # mylist is just another name pointing to the same object!del shoplist[0]print 'shoplist is', shoplistprint 'mylist is', mylist# notice that both shoplist and mylist both print the same list without# the 'apple' confirming that they point to the same objectprint 'Copy by making a full slice'mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint 'shoplist is', shoplistprint 'mylist is', mylist# notice that now the two lists are different

输出:

$ python reference.pySimple Assignmentshoplist is ['mango', 'carrot', 'banana']mylist is ['mango', 'carrot', 'banana']Copy by making a full sliceshoplist is ['mango', 'carrot', 'banana']mylist is ['carrot', 'banana']

需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。

原创粉丝点击