Python数据结构--Python学习笔记四
2016-05-01 19:34
656 查看
简介
数据结构基本上就是——它们是可以处理一些 数据 的 结构 。或者说,它们是用来存储一组相关数据的。在Python中有三种内建的数据结构——列表、元组和字典。
列表
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,你在每个项目之间用逗号分割。列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加(append)或删除(del)项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。#!/usr/bin/python #Filename:using_list.py #this is my shopping list shoplist = ['apple','mango','carrot','bannana'] print 'I have',len(shoplist),' items to purchase' print 'These items are:', for item in shoplist: print item, print '\n I also have to buy rice' shoplist.append('rice') print 'My shopping list is now',shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is ',shoplist print 'The first item I will buy is ',shoplist[0] olditem = shoplist[0] del shoplist[0] print 'I bought the ',olditem print 'My shopping list is now',shoplist
输出
[root@fengniu020 test]# python using_list.py I have 4 items to purchase These items are: apple mango carrot bannana I also have to buy rice My shopping list is now ['apple', 'mango', 'carrot', 'bannana', 'rice'] I will sort my list now Sorted shopping list is ['apple', 'bannana', 'carrot', 'mango', 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['bannana', 'carrot', 'mango', 'rice']
元组
元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变#!/usr/bin/python #Filename:using_tuple.py zoo = ('wolf','elephant','penguin') print 'number of animales in the zoo is',len(zoo) new_zoo = ('monkey','dolphin',zoo) print 'Number of animals in the new zoo is',len(new_zoo) print 'all animals in new zoo are',new_zoo print 'Animals brougth from old zoo are',new_zoo[2] print 'Last animal brought from old zoo is ',new_zoo[2][2]
输出
[root@fengniu020 test]# python using_tuple.py number of animales in the zoo is 3 Number of animals in the new zoo is 3 all animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin')) Animals brougth from old zoo are ('wolf', 'elephant', 'penguin') Last animal brought from old zoo is penguin
它如何工作
变量zoo是一个元组,我们看到len函数可以用来获取元组的长度。这也表明元组也是一个序
列。由于老动物园关闭了,我们把动物转移到新动物园。因此,new_zoo元组包含了一些已经在那里的动物和从老动物园带过来的动物。回到话题,注意元组之内的元组不会失去它的身份。
我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作 索引 运算符。我们使用new_zoo[2]来访问new_zoo中的第三个项目。我们使用new_zoo[2][2]来访问new_zoo元组的第三个项目的第三个项目。
含有0个或1个项目的元组。一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (2 , )。
元组与打印语句
#!/usr/bin/python #Filename:print_tuple.py age = 22 name = 'swaroop' print '%s is %d years old '%(name,age) print 'Why is %s playing with that python?'%name
输出
[root@fengniu020 test]# python print_tuple.py swaroop is 22 years old Why is swaroop playing with that python?
它如何工作
print语句可以使用跟着% 符号的项目元组的字符串。这些字符串具备定制的功能。定制让输出满足某种特定的格式。定制可以是% s表示字符串或% d表示整数。元组必须按照相同的顺序来对应这些定制
在大多数时候,你可以只使用% s定制,而让Python来提你处理剩余的事情。这种方法对数同样
奏效。然而,你可能希望使用正确的定制,从而可以避免多一层的检验程序是否正确。
在第二个print语句中,我们使用了一个定制,后面跟着% 符号后的单个项目——没有圆括号。这只在字符串中只有一个定制的时候有效
字典
字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以把不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。
键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序
#!/usr/bin/python #Filename:using_dict.py ab = {'Swaroop':'swaroopch@byte of python.info', 'Larry':'larry@wal.org', 'Matsumoto':'matz@ruby-lang.org', 'Spammer':'spammer@hotmail.com' } print "Swaroop's address is %s "%ab['Swaroop'] ab['Guido'] = 'guido@python.org' del ab['Spammer'] print '\nThere are %d contacts in the address-book\n'%len(ab) for name,address in ab.items(): print 'Contact %s at %s '%(name,address) if 'Guido' in ab: print "\nGuido's address is %s "%ab['Guido']
输出
[root@fengniu020 test]# python using_dict.py Swaroop's address is swaroopch@byte of python.info There are 4 contacts in the address-book Contact Swaroop at swaroopch@byte of python.info Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wal.org Contact Guido at guido@python.org Guido's address is guido@python.org
我们使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。我们抓取这个对,然后分别赋给for..in循环中的变量name和address然后在for-块中打印这些值。
我们可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。你可以使用help(dict)来查看dict类的完整方法列表。
序列
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。#!/usr/bin/python # Filename: seq.py shoplist = ['apple','mango','carrot','banana'] print 'Item 0 is ',shoplist[0] print 'Item 1 is ',shoplist[1] print 'Item 2 is ',shoplist[2] print 'Item 3 is ',shoplist[3] print 'Item -1 is',shoplist[-1] print 'Item -2 is', shoplist[-2] #slicing on a list print 'Item 1 to 3 is',shoplist[1:3] print 'Item 2 to end is ',shoplist[2:] print 'Item 1 to -1 is ',shoplist[1:-1] print 'Item start to end is ',shoplist[:] #slicing on a string name = 'swaroop' print 'characters 1 to 3 is',name[1:3] print 'characters 2 to end is ',name[2:] print 'characters 1 to -1 is ',name[1:-1] print 'characters start to end is',name[:]
输出
[root@fengniu020 test]# python seq.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Item 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'banana'] Item 1 to -1 is ['mango', 'carrot'] Item start to end is ['apple', 'mango', 'carrot', 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop
索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目
引用
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 引用 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。#!/usr/bin/python # Filename: reference.py print 'Simple assignment' shoplist = ['apple','mango','carrot','banana'] mylist = shoplist del shoplist[0] print 'shoplist is ',shoplist print 'my list is ',mylist print 'copy by making a full silce' mylist = shoplist[:] del mylist[0] print 'shoplist is',shoplist print 'mylist is ',mylist
输出
[root@fengniu020 test]# python reference.py Simple assignment shoplist is ['mango', 'carrot', 'banana'] my list is ['mango', 'carrot', 'banana'] copy by making a full silce shoplist is ['mango', 'carrot', 'banana'] mylist is ['carrot', 'banana']
为什么使用切片拷贝和直接引用,结果不一样呢?
因为对象的内存地址不一样
可以通过id()函数实验
In [1]: shoplist = ['apple','mango','carrot','banana'] In [2]: mylist = shoplist In [3]: del shoplist[0] In [4]: print 'shoplist is ',shoplist shoplist is ['mango', 'carrot', 'banana'] In [5]: print 'my list is ',mylist my list is ['mango', 'carrot', 'banana'] In [6]: mylist = shoplist[:] In [7]: id(shoplist) Out[7]: 32386584 In [8]: id(mylist) Out[8]: 32385504 In [9]: mylist = shoplist In [10]: id(mylist) Out[10]: 32386584 In [11]:
它如何工作
你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 引用 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。
字符串的方法
#!/usr/bin/python # Filename: str_m ethods.py name = 'Swaroop' if name.startswith('Swa'): print 'Yes,the string starts with "Swaa"' if 'a' in name: print 'Yes , it contains the string "a"' if name.find('war') != -1: print 'Yes , it contains the string "war"' dellimiter = '_*_' mylist = ['Brazil','Russia','India','China'] print dellimiter.join(mylist)
输出
[root@fengniu020 test]# python str_methods.py Yes,the string starts with "Swaa" Yes , it contains the string "a" Yes , it contains the string "war" Brazil_*_Russia_*_India_*_China
startwith方法是用来测试字符串是否以给定字符串开始。in操作符用来检验一个给定字符串是否为另一个字符串的一部分。
find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。
str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。
相关文章推荐
- 【数据结构】二叉树遍历
- 【数据结构与算法】十六 二叉树遍历 BFS 广度优先 递归算法
- Java千百问_06数据结构(004)_java数据类型的字面值是什么
- 二叉树的线索化算法思想详解
- 【数据结构与算法】十五 二叉树遍历 DFS 深度优先 递归算法
- 时间复杂度和空间复杂度详解
- 数据结构
- 数据结构之链表学习心得
- 数据结构之队列
- Java千百问_06数据结构(003)_什么是基本类型包装器
- 回溯法 -数据结构与算法
- 回溯法 -数据结构与算法
- 二叉树遍历 - 数据结构
- 二叉树遍历 - 数据结构
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构-栈和队列
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构-栈和队列
- 数据结构-线性表
- 数据结构-线性表