您的位置:首页 > 理论基础 > 数据结构算法

A Byte of Python 笔记(7)数据结构:列表、元组、字典,序列

2016-03-31 17:37 996 查看
第9章 数据结构

数据结构,即可以处理一些数据的结构。或者说,它们是用来存储一组相关数据的。

python 有三种内建的数据结构--列表、元组和字典。

list = ['item1', 'item2', 'item3', 'item4']

len(list) 列表长度

list.append('item5') 为列表添加一个项目

sort(list) 对列表进行排序

del(list[0]) 删除列表中的第一个元素

tuple = ('item1', 'item2', 'item3', 'item4')

dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}

列表

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

列表是 可变的 数据类型,项目包括在方括号中,用户可以添加、删除或搜索列表中的项目。

列表是使用对象和实例的一个例子。当你使用变量 i 并给它赋值时,比如 i=5,你可以认为你创建了一个类(类型) int 的对象(实例)i。

类也有方法,即仅仅为类而定义的函数。类的对象可以使用这些功能。如,python 为 list 类提供了 append 方法,该方法可以让用户在列表尾添加一个项目。

mylist.append('an item'),在列表 mylist 中增加字符串,此处使用点号来使用对象的方法。

类也有域,它是仅为类而定义的变量。只有类的对象可以使用这些变量/名称。类通过点号使用,如 mylist.field。

# -*- coding: utf-8 -*-
# Filename: using_list.py

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

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

print 'These items are:',
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






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

列表(list)是一个序列

print 语句结尾使用逗号(,) 来消除每个 print 语句自动打印的换行符

列表是 可变的 而字符串是 不可变的。

元组

元组和列表类似,但元组和字符串一样是 不可变的,即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。

元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

# -*- coding: utf-8 -*-
# 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]






zoo 是一个元组,len 函数可以用来获取元组的长度。元组也是一个序列。

可以通过 索引 运算符指明某个项目的位置来访问元组中的项目。

含有 0个 或 1个 项目的元组:

一个空的元组,由一对空的圆括号组成,如 myempty = ()

含有单个元素的元组,必须在第一个(唯一一个)项目后跟一个逗号,如 singleton = (2, ),这样才能区分元组和表达式中一个带圆括号的对象。

元组与打印语句

元组最通常的用法是用在打印语句中。

# -*- coding: utf-8 -*-
# Filename: print_tuple.py

age = 2
name = 'Tom'

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






print 语句可以使用跟着 % 符号的项目元组的字符串。这些字符串具备定制的功能。定制让输出满足某种特定的格式。

定制可以是 %s 表示字符串 或 %d 表示整数,元组必须按照相同的顺序来对应这些定制。

python 在这里所做的是把元组中的每个项目转换成字符串并且用字符串的值替换定制的位置。

字典

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的。

注意:字典的键必须是不可变的对象(如,字符串),字典的值可以是 不可变或可变的对象。

键值对在字典中以 d = {key1:value1, key2:value2} 的方式标记。

字典中的 键/值对 是没有顺序的,如果想要制定顺序,应该在使用前进行排序。

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

# -*- coding: utf-8 -*-
# Filename: using_dict.py

# 'ab' is short of 'address book'
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'] = 'guid@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:
print "\nGuido's address is %s" % ab['Guido']

print '\nab.items():', ab.items()






ab['new_key'] = 'new_value' 增加新的键值对

del['key1'] 删除键/值对,无需知道键所对应的值。

使用 items() 方法来使用字典中的每个键值对,返回一个元组的列表,其中每个元组都包含一对项目--键与对应的值

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

关键字参数与字典

如果换一个角度看待你在函数中使用的关键字参数的话,你已经使用字典了!只需想一下——你在函数定义的参数列表中使用的键/值对。当你在函数中使用变量的时候,它只不过是使用一个字典的键(这在编译器设计的术语中被称作 符号表 )。

序列

序列的两个主要特点是 索引操作符 和 切片操作符,列表、元组和字符串都是序列。

索引操作符:可以从序列中抓取一个特定的项目;

切片操作符:能够获取序列的一个切片,即一部分序列。

# -*- coding:utf-8 -*-
# Filename: seq.py

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

# 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[1:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]

# Slicing on a string
name = 'swaroop'
print 'name is', name
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 会为你抓取序列中对应位置的项目。

注意:python 从 0 开始计数,因此 shoplist[0] 抓取第1个元素,shoolist[3] 抓取第4个元素。

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

切片操作符 [m : n],m n是可选的,冒号是必须的。m 表示切片的开始位置,n 表示切片的结束位置,如果不指定 m,从序列首开始;如果不指定 n,到序列尾停止。

注意:返回序列从开始位置 开始,在结束 位置之前结束。即开始位置是包含在序列切片中的,结束位置被排斥在切片外。

参考

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

# -*- coding: utf-8 -*-
# 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]

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






如果你想复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都参考同一个对象,使用赋值语句即可。

记住列表的赋值语句不创建拷贝。你得使用切片操作符来建立序列的拷贝。
更多字符串的内容

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

程序中使用的字符串都是 str 类的对象。可以通过 help(str) 了解 str 方法的完整列表。

# -*- coding: utf-8 -*-
# Filaneme: str_methods.py

name = 'swaroop'

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)






startswith 方法 用来测试字符串是否以给定字符串开始

in 操作符 用来检验一个给定字符串是否为另一个字符串的一部分

find 方法 用来找出给定字符串在另一个字符串中的位置,返回 –1 表示找不到子字符串

str 类 有一个作为分隔符的字符串 join 序列的项目的整洁方法,返回一个生成的大字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: