现在的位置: 首页 > 综合 > 正文

python 学习笔记 3 — 数据结构篇

2013年03月17日 ⁄ 综合 ⁄ 共 5664字 ⁄ 字号 评论关闭

数据结构是可以处理一些 数据 的 结构 。或者说,它们是用来存储一组相关数据的。在Python中有三种内建的数据结构——列表、元组和字典。本文主要对这三种数据类型以及相关的使用做介绍,以例子的形式演示更加容易理解!

1.列表(List)

列表是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。在Python中,你在每个项目之间用逗号分割

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

shoplist = ['apple', 'mango', 'carrot', 'banana']         # 定义一个shoplist列表!
for item in shoplist:	print item,		# 打印列表项(print末尾添加“,”可以消除print的换行符)
shoplist.append('rice')	                        # 添加列表项
shoplist.sort()		                        # 对列表进行排序
del shoplist[0]		                        # 删除列表某一项(从0开始记数,所以这条命令删除列表中第一个元素)

2.元组

元组和列表十分类似,只不过元组和字符串一样是 不可变的--- 即你不能修改元组。元组通过**圆括号**中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

eg1.

zoo = ('wolf', 'elephant', 'penguin')	# 定义元组
	new_zoo = ('monkey', 'dolphin', zoo)	# 元组中也可以使用元组作为元素,其实这就类似于二位数组了!比如我们想通过new_zoo打印zoo元组可以使用new_zoo[2],而如果想打印zoo中的‘wolf’就可以使用new_zoo[2][0],是不是与二位数组非常相似?


eg2. 下面演示的是元组一般用法 -- 打印时使用!相似方法在上一节判断语句的示例中使用过!

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)	# print语句可以使用跟着%符号的项目元组的字符串。这些字符串具备定制的功能。定制让输出满足某种特定的格式。定制可以是%s表示字符串或%d表示整数。元组必须按照相同的顺序来对应这些定制。


3.字典(Dict)

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。

注:(1) 你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以把不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。
    (2) 键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
    (3) 记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

eg.

# -*- coding: utf-8 -*-
ab = {  'Swaroop' : 'swaroopch@byteofpython.info',
    'Larry' : 'larry@wall.org',
    'Matsumoto' : 'matz@ruby-lang.org',
    'Spammer' : 'spammer@hotmail.com',
    'Longerzone' : 'reaper888@yeah.net'
}
print "Longerzone's address is %s" % ab['Longerzone']
ab['Guido'] = 'guido@python.org'        # 添加字典条目
del ab['Spammer']                       # 删除字典条目,我们只需要指明字典和用索引操作符指明要删除的>键,然后把它们传递给del语句就可以了。执行这个操作的时候,我们无需知道那个键所对应的值。
print "Now we will print the dict:\n"
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

此处的运行效果是:

long@zhouyl:~/python_project/python_test$ python dict.py
Longerzone's address is reaper888@yeah.net
Now we will print the dict:

Contact Matsumoto at matz@ruby-lang.org
Contact Longerzone at reaper888@yeah.net
Contact Swaroop at swaroopch@byteofpython.info
Contact Larry at larry@wall.org
Contact Guido at guido@python.org

4.序列

列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目切片操作符让我们能够获取序列的一个切片,即一部分序列。
eg.

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

4.1.索引描述符

使用索引来取得序列中的单个项目。这也被称作是下标操作。每当你用方括号中的一个数来指定一个序列的时候,Python会为你抓取序列中对应位置的项目。

print 'Item 0 is', shoplist[0]    	# shoplist[0]抓取第一个项目
print 'Item 1 is', shoplist[1]   	# shoplist[0]抓取第二个项目
print 'Item 2 is', shoplist[2]   	# shoplist[0]抓取第三个项目
print 'Item 3 is', shoplist[3]   	
print 'Item -1 is', shoplist[-1]	# 索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。

这里的运行结果如下:

long@zhouyl:~$ vim /tmp/split1.py
long@zhouyl:~$ python /tmp/split1.py 
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana

4.2.切片描述符

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

# Slicing on a list		                 # 在一个列表上切片
print 'Item 1 to 3 is', shoplist[1:3]	         # shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置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[:]	 # 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[:]

这里的运行结果如下:

long@zhouyl:~$ vim /tmp/split.py
long@zhouyl:~$ python /tmp/split.py 
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

5.引用

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

# -*- coding: utf-8 -*-
shoplist = ['apple', 'mango', 'carrot', 'banana']
print "we copy the shoplist to mylist directly \"with mylist = shoplist\" "
mylist = shoplist                         # 直接使用等于,此时mylist与shoplist只是指向一个对象的两个名字
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist
print "delete the first item of shoplist"
del shoplist[0]                           # 此时删除shoplist 或者mylist 中的元素效果是一样的,都会对那个列表对象直接进行操作
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist

print "\nThis time we use slice to cope the shoplist \"with mylist = shoplist[:]\" "
mylist = shoplist[:]                      # 使用一个完整的切片复制,此时mylist只是与shoplist有一样的内容的两个对象!
print "delete the first item of mylist"
del mylist[0]                             # 此时删除mylist中的元素不会对shoplist中的元素造成影响!
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist

运行的结果如下:

long@zhouyl:~/python_test$ python cite.py 
we copy the shoplist to mylist directly "with mylist = shoplist" 
	Now the shoplist is : ['apple', 'mango', 'carrot', 'banana']
	Now the mylist is : ['apple', 'mango', 'carrot', 'banana']
delete the first item of shoplist
	Now the shoplist is : ['mango', 'carrot', 'banana']
	Now the mylist is : ['mango', 'carrot', 'banana']

This time we use slice to cope the shoplist "with mylist = shoplist[:]" 
delete the first item of mylist
	Now the shoplist is : ['mango', 'carrot', 'banana']
	Now the mylist is : ['carrot', 'banana']

6.字符串的方法

字符串也是对象,同样具有方法。这些方法可以完成包括检验一部分字符串和去除空格在内的各种工作。

eg.

# -*- coding: utf-8 -*-
name = 'longerzone'                                # 先定义一个字符串
if name.startswith('lon'):                         # startwith 用来测试字符串是否以给定字符串开始。
    print 'Yes, the string starts with "lon"'
if 'z' in name:                                    # in操作符用来检验一个给定字符串是否为另一个字符串的一部分
    print 'Yes, it contains the string "z"'
if name.find('zon') != -1:                         # find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。
    print 'Yes, it contains the string "zon"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)                       # str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。

这里的运行结果如下:

long@zhouyl:~/python_test$ python string.py
Yes, the string starts with "lon"
Yes, it contains the string "z"
Yes, it contains the string "zon"
Brazil_*_Russia_*_India_*_China


注:本文主要以例子的形式介绍了几种python的数据结构,只能作为简单了解,想跟熟悉使用还需您自己好好练习,多阅读好代码!

抱歉!评论已关闭.