6.1、List

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

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

列表是使用对象和类的一个例子。当你使用变量i并给它赋值的时候,比如赋整数5,你可以认为你创建了一个(类型)int对象(实例)i。事实上,你可以看一下help(int)以更好地理解这一点。

类也有方法,即仅仅为类而定义地函数。仅仅在你有一个该类的对象的时候,你才可以使用这些功能。例如,Python为list类提供了append方法,这个方法让你在列表尾添加一个项目。例如mylist.append('an item')列表mylist中增加那个字符串。注意,使用点号来使用对象的方法。

一个类也有,它是仅仅为类而定义的变量。仅仅在你有一个该类的对象的时候,你才可以使用这些变量/名称。类也通过点号使用,例如mylist.field

list类的方法:

append(x)  把一个元素添加到链表的结尾,相当于a[len(a):] = [x]

extend(L) 通过添加指定链表的所有元素来扩充链表,相当于a[len(a):] = L

实例:

#!/usr/bin/python

a
=[1,2]
b
=['a','b']
a.extend(b)
print a

输出:

[1,2,'a','b']

insert(i,x) 在指定位置i插入一个元素x,如a.insert(0,0)会插入到整个链表之前,而a.insert(len(a),'c')相当于a.append('c')。

remove(x)  删除链表中值为x的第一个元素,如果没有这样的元素,就会返回一个错误。

pop([i])  从链表的指定位置删除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素,元素随即从链表中被删除。方法中i两加的括号表示参数可选,而不是要输入一对括号。

index(x)  返回链表中第一个值为x的元素的索引。注:链表的索引是从0开始记数的.如果没有匹配的元素就会返回一个错误。

count(x)  返回x元素在链表中出现的次数。

sort()  对链表中的元素就地进行排序。

reverse()  就地倒排链表中的元素。

使用链表:

实例1:

#!/usr/bin/python
#
-*-coding:utf-8-*-
#
us_list.py
list=[]
list.append(
1)
print "把元素1添加到空的链表list结尾"
print "这时list链表中第一个值是1的索引:",list.index(1)
print "list中第一个元素:",list[0]

list.extend([
2,3,4])
print "扩充list链表后,输出链表中的所有元素:"
for I in range(0,len(list)):
print list[I]

list.insert(0,0)
print "在链表首加入元素'0',输出list当前第一个元素:",list[0]

list.insert(len(list),
'a')
print "在链表尾加入元素'a',输出list结尾元素:",list[len(list)-1]

print list.pop(-2)
print list.pop()
list.remove(
3)

list.reverse()
print list
list.sort()
print list

list.append(
2)
print list

print list.count(2)

输出:

把元素1添加到空的链表list结尾
这时list链表中第一个值是1的索引: 0
list中第一个元素: 1
扩充list链表后,输出链表中的所有元素:
1
2
3
4
在链表首加入元素'0',输出list当前第一个元素: 0
在链表尾加入元素'a',输出list结尾元素: a
4
a
[2, 1, 0]
[0, 1, 2]
[0, 1, 2, 2]
2

6.1.1、把链表当作堆栈使用

堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出)。用append()方法把一个元素添加到堆栈顶,用不指定索引的pop()方法把一个元素从堆栈顶释放出来。

实例:

#!/usr/bin/python
#
Filename: stack.py

stack
= []
stack.append(0)
stack.append(
1)
stack.append(
3)
print stack[:]

print stack.pop()
print stack.pop()
print stack.pop()
print stack[:]

输出:

[0, 1, 3]
3
1
0
[]

6.1.2、把链表当作队列使用

队列作为特定的数据结构,最先进入的元素最先释放(先进先出)。用append()方法把一个元素添加到队列最后,以0为索引参数调用pop()方法把最先进入的元素释放出来。

实例:

#!/usr/bin/python
#
Filename: queue.py

queue
= []
queue.append(0)
queue.append(
1)
queue.append(
3)
print queue[:]

print queue.pop(0)
print queue.pop(0)
print queue.pop(0)
print queue[:]

输出:

[0, 1, 3]
0
1
3
[]

6.2、元组

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

#!/usr/bin/python
#
Filename: using_tuple.py

zoo
= ('wolf', 'elephant', 'penguin')
print 'Number of animals 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 brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]

输出:

Number of animals 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 brought 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 , )

6.3、字典

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

注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。

键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

字典是dict类的实例/对象。

实例:

#!/usr/bin/python
#
Filename: using_dict.py

# 'ab' is short for 'a'ddress'b'ook

ab
= { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}

print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair
ab['Guido'] = 'guido@python.org'

# Deleting a key/value pair
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: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']

输出:

Swaroop's address is swaroopch@byteofpython.info

There are 4 contacts in the address-book

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

Guido's address is guido@python.org

字典还可以这样操作:

a = {}
a['a'] = 'aaa'
print a
a['a'] += 'aaa'
print a

输出:

{'a': 'aaa'}
{'a': 'aaaaaa'}

6.4、序列

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

实例:

#!/usr/bin/python
#
Filename: seq.py

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

# Indexing or 'Subscription' operation
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[:]

输出:

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

首先,我们来学习如何使用索引来取得序列中的单个项目。这也被称作是下标操作。每当你用方括号中的一个数来指定一个序列的时候,Python会为你抓取序列中对应位置的项目。记住,Python从0开始计数。因此,shoplist[0]抓取第一个项目,shoplist[3]抓取shoplist序列中的第四个元素。

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

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

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

这样,shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置3的一个序列切片,因此返回一个含有两个项目的切片。类似地,shoplist[:]返回整个序列的拷贝。

你可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1]会返回除了最后一个项目外包含所有项目的序列切片。

使用Python解释器交互地尝试不同切片指定组合,即在提示符下你能够马上看到结果。序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。

 

6.5、什么是参考?

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。一般说来,你不需要担心这个,只是在参考上有些细微的效果需要你注意。这会通过下面这个例子加以说明。

实例:

#!/usr/bin/python
#
Filename: reference.py

print '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', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
#
the 'apple' confirming that they point to the same object

print 'Copy by making a full slice'
mylist
= shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different

输出:

Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

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

6.6、字符串

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

你在程序中使用的字符串都是str类的对象。这个类的一些有用的方法会在下面这个例子中说明。如果要了解这些方法的完整列表,请参见help(str)

实例:

#!/usr/bin/python
#
Filename: str_methods.py

name
= 'Swaroop' # This is a string object

if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'

if 'a' in name:
print 'Yes, it contains the string "a"'

if name.find('war') != -1:
print 'Yes, it contains the string "war"'

delimiter
= '_*_'
mylist
= ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)

输出:

Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

startwith方法是用来测试字符串是否以给定字符串开始。in操作符用来检验一个给定字符串是否为另一个字符串的一部分。

find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。

posted on 2011-08-16 16:03  xunya  阅读(963)  评论(0)    收藏  举报