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

(六)《A Byte of Python》——数据结构

2018-01-17 16:33 585 查看
数据结构,即用来存储一系列相关数据的集合 。
1. 列表
        是一种用于保存一系列有序项目的集合,也就是说,你可以利用列表保存一串项目的序列。在Python中需要在它们之间多加上一个逗号。项目的列表应该用方括号括起来,这样Python才能理解到你正在指定一张列表。一旦创建了一张列表,便可以添加、移除或搜索列表中的项目。列表是一种可变的(Mutable) 数据类型,意即,这种类型是可以被改变的。 
        列表是使用对象与类的实例。当我们启用一个变量i并将整数5赋值给它时,你可以认为这是在创建一个int类(即类型)之下的对象(即实例)i。一个类也可以带有方法(Method) ,也就是说对这个类定义仅对于它启用某个函数。只有当你拥有一个属于该类的对象时,你才能使用这些功能。举个例子,Python为list类提供了一种append方法,能够允许你向列表末尾添加一个项目。例如mylist.append('an item')将会向列表mylist添加一串字符串。在这里要注意到我们通过使用点号的方法来访问对象。一个类同样也可以具有字段(Field),它是只为该类定义且只为该类所用的变量。只有当你拥有一个属于该类的对象时,你才能够使用这些变量或名称。字段同样可以通过点号来访问,例如mylist.field。
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('These items are:', end=' ') #末尾不换行加空格
for item in shoplist:
print(item, end=' ')
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 ds_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']

classmates.append 在末尾加入元素;
classmates.insert(1, 'Jack') 把元素加入指定位置;
classmates.pop() 删除末尾元素

classmates.pop(1) 删除指定位置元素

 classmates[1] = 'Sarah' 把某个元素替换成别的元素

2. 元组

       元组(Tuple) 用于将多个对象保存到一起。你可以将它们近似地看作列表,但是元组不能提供列表类能够提供给你的广泛的功能。元组的一大特征类似于字符串,它们是不可变的,也就是说,你不能编辑或更改元组。元组是通过特别指定项目来定义的,在指定项目时,你可以给它们加上小括号,并在括号内部用逗号进行分隔。通常用于保证某一语句或某一用户定义的函数可以安全地采用一组数值,即元组内的数值不会改变。
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
print('Number of cages 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])
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))
$ python ds_using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5
3. 字典
        将键值(Keys) (即姓名) 与值(Values) (即地址等详细信息) 联立到一起。在这里要注意到键值必须是唯一的 。只能使用不可变的对象(如字符串) 作为字典的键值,但是可以使用可变或不可变的对象作为字典中的值。可以理解为你只能使用简单对象作为键值。在字典中,你可以通过使用符号构成d = {key : value1 , key2 : value2}这样的形式,来成对地指定键值与值。在这里要注意到成对的键值与值之间使用冒号分隔,而每一对键值与值则使用逗号进行区分,全都由一对花括号括起。字典中的成对的键值—值配对不会以任何方式进行排序。如果你希望为它们安排一个特别的次序,只能在使用前自行排序 。
# “ab”是地址(Address) 簿(Book) 的缩写
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is", ab['Swaroop'])
# 删除一对键值—值配对
del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name, address in ab.items():
print('Contact {} at {}'.format(name, address))
# 添加一对键值—值配对
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab: #检查某对键值—值配对是否存在
print("\nGuido's address is", ab['Guido'])
$ python ds_using_dict.py
Swaroop's address is swaroop@swaroopch.com
There are 3 contacts in the address-book
Contact Swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Guido's address is guido@python.org
         item方法——把字典中每对key和value组成一个元组,并把这些元组放在列表中返回。
4. 序列
        序列的主要功能是资格测试(Membership Test)(也就是in与not in表达式) 和索引操作(Indexing Operations) ,它们能够允许我们直接获取序列中的特定项目。上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing) 运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
# 索引或“下标(Subcription) ”操作符 #
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]) #shoplist[-1] 指的是序列的最后一个项目
print('Item -2 is', shoplist[-2]) #shoplist[-2] 将获取序列中倒数第二个项目
print('Character 0 is', name[0])
# 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[:])
# 从某一字符串中切片 #
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 ds_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
Character 0 is s
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将会在序列的末尾结束操作。可以在切片操作中提供第三个参数,这一参数将被视为切片的步长(Step),默认为1。 

5. 集合        集合(Set) 是简单对象的无序集合(Collection) 。当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合。通过使用集合,你可以测试某些对象的资格或情况,检查它们是否是其它集合的子集,找到两个集合的交集等等。 
>>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}
        bric.issuperset指超集:如果一个集合S2中的每一个元素都在集合S1中,且集合S1中可能包含S2中没有的元素,则集合S1就是S2的一个超集,反过来,S2是S1的子集。 S1是S2的超集,若S1中一定有S2中没有的元素,则S1是S2的真超集,反过来S2是S1的真子集。返回TRUE或者FALSE。6. 引用
        当你创建了一个对象并将其分配给某个变量时,变量只会查阅(Refer) 某个对象,并且它也不会代表对象本身。也就是说,变量名只是指向你计算机内存中存储了相应对象的那一部分。这叫作将名称绑定(Binding)给那一个对象。
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist 只是指向同一对象的另一种名称
mylist = shoplist
# 我购买了第一项项目,所以我将其从列表中删除
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到 shoplist 和 mylist 二者都
# 打印出了其中都没有 apple 的同样的列表,以此我们确认它们指向的是同一个对象
print('Copy by making a full slice')
# 通过生成一份完整的切片制作一份列表的副本
mylist = shoplist[:]
# 删除第一个项目
del mylist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到现在两份列表已出现不同
$ python ds_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']
7. 其他
# 这是一个字符串对象
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))
$ python ds_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
       startwith 用于查找字符串是否以给定的字符串内容开头。in运算符用以检查给定的字符串是否是查询的字符串中的一部分。find方法用于定位字符串中给定的子字符串的位置。如果找不到相应的子字符串,find会返回-1。str类同样还拥有一个简洁的方法用以联结(Join)序列中的项目,其中字符串将会作为每一项目之间的分隔符,并以此生成并返回一串更大的字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: