Python读书笔记第九章:数据结构

1.列表

Python中有三种内建的数据结构:列表、元组和字典。列表是处理一组有序项目的数据结构。列表的项目应该包括在方括号中,这样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

$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

我们使用for..in循环在列表中各项目间递归,在print的语句的结尾使用了一个都逗号来消除每个print语句自动打印的换行符。打印列表只需简单地把列表传递给print语句即可。

使用append方法在列表中添加一个项目,再接下来使用sort方法来对列表排序,这个方法影响列表本身,而不是返回一个修改的列表。最后使用del语句来删除。

如果想要知道列表的所有方法,可以通过help(list)来获取。


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]

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

len函数可以用来获取序列的长度,包括列表、元组等。元组之内的元组不会失去它的身份,我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,new_zoo[2]访问new_zoo的第三个项目,new_zoo[2][2]访问第三个项目的第三个项目。

一个空的元组由一对空的圆括号组成,只有单个元素的元组必须在元组项目后跟一个逗号。var = (), single = (1, )


打印语句

#!/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

输出:

$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?

print语句可以使用跟着%符号的字符串,这些字符串具备定制功能,使输出满足某种特定的格式,类似与C的printf。


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

$ 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

我们可以使用索引操作符(一对方括号)来寻址一个键并为它赋值,这样就增加了一个新的键值对,del用于删除,只需指明要删除的键即可。

我们还可以使用字典的items方法,来使用字典中的每个键值对,这样会返回一个元组的列表,然后抓取这个对用for...in循环来打印。

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


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[:]

输出:

$ 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

索引可以是复数,表示位置是从序列尾开始计算,-1表示序列的最后一个元素,-2表示序列的倒数第二个元素

切片操作符是序列名跟一个方括号,方括号有一对可选的数字,并用冒号分割。数是可选的,冒号是必须的。如果不指定第一个数表示序列首,不指定第二个数表示序列尾,第二个数是开区间的。

同样可以用负数做切片,复负数用在从序列尾开始计算的位置。


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

输出:
$ python reference.py
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.更多字符串的内容

字符串都是str类的对象。startwith方法用来测试字符串是否以给定字符串开始,in操作符用来检验一个给定字符串是否为另一个字符串的一部分,find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1表示找不到字符串,str类还有一个作为分隔符的字符串join序列的项目的整洁方法,它返回一个生成的大字符串。

#!/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)
输出:

$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值