Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1456783
  • 博文数量: 408
  • 博客积分: 10036
  • 博客等级: 上将
  • 技术积分: 4440
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-06 13:57
文章分类

全部博文(408)

文章存档

2011年(1)

2010年(2)

2009年(1)

2008年(3)

2007年(7)

2006年(394)

我的朋友

分类: Python/Ruby

2006-07-24 17:42:30

Python 简明教程——数据结构
Python有三种内建的数据结构——列表、元组和字典。
 

列表

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

列表中的项目应该包括在方括号中。一旦创建了一个列表,可以执行添加、删除或是搜索列表中的项目等操作。

的例子:

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

# This is my shopping list

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

print 'I have', len(shoplist),'items to purchase.'

print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
    print item,

print '\nI 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

可以在列表中添加 任何种类的对象 包括数甚至其他列表。

可以使用了for..in循环在列表中各项目间递归。

print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。

如果想要知道列表对象定义的所有方法,可以通过help(list)获得完整的知识。

 

元组

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

的例子

#!/usr/bin/python

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
 
 

含有0个或1个项目的元组。一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。

元组最通常的用法是用在打印语句中,下面是一个例子:
的例子:
#!/usr/bin/python

age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

 

字典

字典把(名字)和(详细情况)联系在一起。字典的键只能使用不可变的对象(比如字符串)。

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

字典中的键/值对是没有顺序的。

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

的例子:

#!/usr/bin/python

# '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']

输出

$ python using_dict.py
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

字典的items方法可以用来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。将它们分别赋给for..in循环中的变量nameaddress然后在for-块中打印这些值。

可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。

可以使用help(dict)来查看dict类的完整方法列表。

 

字符串

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

程序中使用的字符串都是str类的对象。如果要了解这些方法的完整列表,可以参见help(str)

#!/usr/bin/python
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

 

序列

列表、元组和字符串都是序列,序列的两个主要特点是索引操作符和切片操作符。索引操作符可以从序列中抓取一个特定项目。切片操作符能够获取序列的一个切片,即一部分序列

的例子

#!/usr/bin/python
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

 

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

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。数是可选的,而冒号是必须的。

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

序列的神奇之处在于可以用相同的方法访问元组、列表和字符串。

 

引用

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

对象与引用

#!/usr/bin/python

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']

 

如果要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象),那么必须使用切片操作符来取得拷贝。列表的赋值语句创建拷贝,必须使用切片操作符来建立序列的拷贝。

阅读(1042) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~