微信公众号: 点击蓝色字体小白图像与视觉进行关注
关于技术、关注
yysilence00
。有问题或建议,请公众号留言
下面主要讲数据结构
- 整理知识,学习笔记
- 发布日记,杂文,所见所想
. 数据结构 {#data-structures}
Python 中有四种内置的数据结构——列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)。
列表有关对象与类的快速介绍元组字典序列 {#sequence}集合引用有关字符串的更多内容 {#more-strings}总结
. 列表
列表
是一种用于保存一系列有序项目的集合,也就是说,你可以利用列表保存一串项目的序列。想象起来也不难,你可以想象你有一张购物清单,上面列出了需要购买的商品,除开在购物清单上你可能为每件物品都单独列一行,在 Python 中你需要在它们之间多加上一个逗号。
项目的列表应该用方括号括起来,这样 Python 才能理解到你正在指定一张列表。一旦你创建了一张列表,你可以添加、移除或搜索列表中的项目。既然我们可以添加或删除项目,我们会说列表是一种可变的(Mutable)数据类型,意即,这种类型是可以被改变的。
. 有关对象与类的快速介绍
虽然到目前为止我经常推迟有关对象(Object)与类(Class)的讨论,但现在对它们进行稍许解释能够有助于你更好地理解列表。
列表是使用对象与类的实例。当我们启用一个变量 i
并将整数 5
赋值给它时,你可以认为这是在创建一个 int
类(即类型)之下的对象(即实例) i
。实际上,你可以阅读 help(int)
来了解更多内容。
一个类也可以带有方法(Method),也就是说对这个类定义仅对于它启用某个函数。只有当你拥有一个属于该类的对象时,你才能使用这些功能。举个例子,Python 为 list
类提供了一种 append
方法,能够允许你向列表末尾添加一个项目。例如 mylist.append('an item')
将会向列表 mylist
添加一串字符串。在这里要注意到我们通过使用点号的方法来访问对象。
一个类同样也可以具有字段(Field),它是只为该类定义且只为该类所用的变量。只有当你拥有一个属于该类的对象时,你才能够使用这些变量或名称。字段同样可以通过点号来访问,例如 mylist.field
。
案例(保存为 ds_using_list.py
):
1"""
2列表list
3
4x[index], x[index:index], x(arguments...), x.attribute :下标、切片、调用、属性引用
5
6(expressions...), [expressions...], {key: value...}, {expressions...} :表示绑定或元组、表示列表、表示字典、表示集合
7"""
8# This my shopping list
9shoplist = ['apple', 'mango', 'carrot', 'banana']
10
11print('I have', len(shoplist), 'items to purchase.')
12
13print('Thesre items are:', end=' ')
14for item in shoplist:
15 print(item, end=' ')
16
17print('\n\nI also have to buy rice.\n')
18shoplist.append('rice')
19# shoplist.append(['fish', 'egg']) 你可以向列表中添加任何类型的 对象,包括数字,甚至是其它列表。但是后面的sort()不支持list与str两种实例
20print('my shopping list is now', shoplist)
21
22
23print('i will sort my list now')
24shoplist.sort()
25print('sorted shopping list is', shoplist)
26
27print('The first item I will buy is', shoplist[0])
28olditem = shoplist[0]
29del shoplist[0]
30print('I bought the', olditem)
31print('My shopping list is now', shoplist)
输出:
1I have 4 items to purchase.
2Thesre items are: apple mango carrot banana
3
4I also have to buy rice.
5
6my shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
7i will sort my list now
8sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
9The first item I will buy is apple
10I bought the apple
11My shopping list is now ['banana', 'carrot', 'mango', 'rice']
变量 shoplist
是一张为即将前往市场的某人准备的购物清单。在 shoplist
中,我们只存储了一些字符串,它们是我们需要购买的物品的名称,但是你可以向列表中添加任何类型的对象,包括数字,甚至是其它列表。
我们还使用 for...in
循环来遍历列表中的每一个项目。学习到现在,你必须有一种列表也是一个序列的意识。
在这里要注意在调用 print
函数时我们使用 end
参数,这样就能通过一个空格来结束输出工作,而不是通常的换行。
接下来,如我们讨论过的那般,我们通过列表对象中的 append
方法向列表中添加一个对象。然后,我们将列表简单地传递给 print
函数,整洁且完整地打印出列表内容,以此来检查项目是否被切实地添加进列表之中。
接着,我们列表的 sort
方法对列表进行排序。在这里要着重理解到这一方法影响到的是列表本身,而不会返回一个修改过的列表——这与修改字符串的方式并不相同。同时,这也是我们所说的,列表是可变的(Mutable)而字符串是不可变的(Immutable)。
随后,当我们当我们在市场上买回某件商品时,我们需要从列表中移除它。我们通过使用 del
语句来实现这一需求。在这里,我们将给出我们希望从列表中移除的商品,del
语句则会为我们从列表中移除对应的项目。我们希望移除列表中的第一个商品,因此我们使用 del shoplist[0]
(要记住 Python 从 0 开始计数)。
如果你想了解列表对象定义的所有方法,可以通过 help(list)
来了解更多细节。
. 元组
元组(Tuple)用于将多个对象保存到一起。你可以将它们近似地看作列表,但是元组不能提供列表类能够提供给你的广泛的功能。元组的一大特征类似于字符串,它们是不可变的,也就是说,你不能编辑或更改元组。
元组是通过特别指定项目来定义的,在指定项目时,你可以给它们加上括号,并在括号内部用逗号进行分隔。
元组通常用于保证某一语句或某一用户定义的函数可以安全地采用一组数值,意即元组内的数值不会改变。
案例(保存为 ds_using_tuple.py
):
1"""
2元组tuple
3
4x[index], x[index:index], x(arguments...), x.attribute :下标、切片、调用、属性引用
5
6(expressions...), [expressions...], {key: value...}, {expressions...} :表示绑定或元组、表示列表、表示字典、表示集合
7# 我会推荐你总是使用括号
8# 来指明元组的开始与结束
9# 尽管括号是一个可选选项。
10# 明了胜过晦涩,显式优于隐式。
11
12"""
13zoo = ('python', 'elephant', 'penguin')
14
15print('number of animals in the zoo is', len(zoo))
16
17new_zoo = 'monkey', 'camel', zoo
18#new_zoo = ('monkey', 'camel', zoo)
19print('number of cages in the new zoo is', len(new_zoo))
20print('All animals in new zoo are', new_zoo)
21
22print('Animals brought from old zoo are', new_zoo[2])
23print('First animal brought from old zoo is', new_zoo[2][0])
24print('Sencond brought from old zoo is', new_zoo[2][1])
25print('Last animal brought from old zoo is', new_zoo[2][2])
26print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
输出:
1number of animals in the zoo is 3
2number of cages in the new zoo is 3
3All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
4Animals brought from old zoo are ('python', 'elephant', 'penguin')
5First animal brought from old zoo is python
6Sencond brought from old zoo is elephant
7Last animal brought from old zoo is penguin
8Number of animals in the new zoo is 5
变量 zoo
指的是一个包含项目的元组。我们能够看到 len
函数在此处用来获取元组的长度。这也表明元组同时也是一个序列。
现在,我们将这些动物从即将关闭的老动物园(Zoo)转移到新的动物园中。因此,new_zoo
这一元组包含了一些本已存在的动物以及从老动物园转移过去的动物。让我们回到话题中来,在这里要注意到元组中所包含的元组不会失去其所拥有的身份。
如同我们在列表里所做的那般,我们可以通过在方括号中指定项目所处的位置来访问元组中的各个项目。这种使用方括号的形式被称作索引(Indexing)运算符。我们通过指定 new_zoo[2]
来指定 new_zoo
中的第三个项目,我们也可以通过指定 new_zoo[2][2]
来指定 new_zoo
元组中的第三个项目中的第三个项目[1]。一旦你习惯了这种语法你就会觉得这其实非常简单。
包含 0 或 1 个项目的元组
一个空的元组由一对圆括号构成,就像
myempty = ()
这样。然而,一个只拥有一个项目的元组并不像这样简单。你必须在第一个(也是唯一一个)项目的后面加上一个逗号来指定它,如此一来 Python 才可以识别出在这个表达式想表达的究竟是一个元组还是只是一个被括号所环绕的对象,也就是说,如果你想指定一个包含项目2
的元组,你必须指定singleton = (2, )
。
. 字典
在字典中,你可以通过使用符号构成 d = {key : value1 , key2 : value2}
这样的形式,来成对地指定键值与值。在这里要注意到成对的键值与值之间使用冒号分隔,而每一对键值与值则使用逗号进行区分,它们全都由一对花括号括起。
另外需要记住,字典中的成对的键值—值配对不会以任何方式进行排序。如果你希望为它们安排一个特别的次序,只能在使用它们之前自行进行排序。
你将要使用的字典是属于 dict
类下的实例或对象。
案例(保存为 ds_using_dict.py
):
1"""
2x[index], x[index:index], x(arguments...), x.attribute :下标、切片、调用、属性引用
3
4(expressions...), [expressions...], {key: value...}, {expressions...} :表示绑定或元组、表示列表、表示字典、表示集合
5"""
6
7# “ab”是地址(Address)簿(Book)的缩写
8ab = {
9 'Swaroop': 'swaroop@swaroopch.com',
10 'Larry': 'larry@wall.org',
11 'Matsumoto': 'matz@ruby-lang.org',
12 'Spammer': 'spammer@hotmail.com'
13}
14
15print("Swaroop's address is", ab['Swaroop'])
16
17# 删除一对键值-值配对
18del ab['Spammer']
19
20print('\nThere are {0} contacts in the address-book\n'.format(len(ab)))
21
22# 字典ab的方法items()调用返回的是一份包含元组的列表
23print(ab.items(),'\n')
24
25for name, address in ab.items():
26 print('Contacts {} at {}'.format(name, address))
27
28# 添加一对键值-值配对 我们可以简单地通过使用索引运算符访问一个键值并为 其分配与之相应的值
29ab['yanyong'] = 'yy@python.org'
30
31if 'yanyong' in ab:
32 print("\nyanyong's address is", ab['yanyong'],'\n')
33
34for name, address in ab.items():
35 print('Contacts {} at {}'.format(name, address))
输出:
1Swaroop's address is swaroop@swaroopch.com
2
3There are 3 contacts in the address-book
4
5dict_items([('Swaroop', 'swaroop@swaroopch.com'), ('Larry', 'larry@wall.org'), ('Matsumoto', 'matz@ruby-lang.org')])
6
7Contacts Swaroop at swaroop@swaroopch.com
8Contacts Larry at larry@wall.org
9Contacts Matsumoto at matz@ruby-lang.org
10
11yanyong's address is yy@python.org
12
13Contacts Swaroop at swaroop@swaroopch.com
14Contacts Larry at larry@wall.org
15Contacts Matsumoto at matz@ruby-lang.org
16Contacts yanyong at yy@python.org
我们通过已经讨论过的符号体系来创建字典 ab
。然后我们通过使用索引运算符来指定某一键值以访问相应的键值—值配对,有关索引运算符的方法我们已经在列表与元组部分讨论过了。你可以观察到这之中的语法非常简单。
我们可以通过我们的老朋友——del
语句——来删除某一键值—值配对。我们只需指定字典、包含需要删除的键值名称的索引算符,并将其传递给 del
语句。这一操作不需要你知道与该键值相对应的值。
接着,我们通过使用字典的 items
方法来访问字典中的每一对键值—值配对信息,这一操作将返回一份包含元组的列表,每一元组中则包含了每一对相应的信息——键值以及其相应的值。我们检索这一配对,并通过 for...in
循环将每一对配对的信息相应地分配给 name
与 address
变量,并将结果打印在 for
代码块中。
如果想增加一堆新的键值—值配对,我们可以简单地通过使用索引运算符访问一个键值并为其分配与之相应的值,就像我们在上面的例子中对 Guido 键值所做的那样。
我们可以使用 in
运算符来检查某对键值—值配对是否存在。
要想了解有关 dict
类的更多方法,请参阅 help(dict)
。
关键字参数与字典
如果你曾在你的函数中使用过关键词参数,那么你就已经使用过字典了!你只要这么想——你在定义函数时的参数列表时,就指定了相关的键值—值配对。当你在你的函数中访问某一变量时,它其实就是在访问字典中的某个键值。(在编译器设计的术语中,这叫作符号表(Symbol Table))
. 序列 {#sequence}
序列的主要功能是资格测试(Membership Test)(也就是 in
与 not in
表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。
序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。
案例(保存为 ds_seq.py
):
1"""
2列表、元组和字符串可以看作序列(Sequence)的某种表现形式,可是究竟什么是序列,它又有什么特别之处?
3"""
4shoplist = ['apple', 'mango', 'carrot', 'banana']
5name = 'Swaroop'
6
7# Indexing or Subscription operation
8# 索引和下标操作符
9print('Item 0 is', shoplist[0])
10print('Item 1 is', shoplist[1])
11print('Item 2 is', shoplist[2])
12print('Item 3 is', shoplist[3])
13print('Item -1 is', shoplist[-1])
14print('Item -2 is', shoplist[-2])
15print('Item -3 is', shoplist[-3])
16print('Item -4 is', shoplist[-4])
17
18print('Character 0 is', name[0])
19
20# slicing 切片运算符 前闭后开
21print('Item 1 to 3 is', shoplist[1:3])
22print('Item 2 to end is', shoplist[2:])
23print('Item 1 to -1 is', shoplist[1:-1])
24print('Item start to end is', shoplist[:])
25print('Item start to -1 is', shoplist[:-1])
26
27# 第三个参数为步长
28print('\nItem start to end is', shoplist[::1])
29print('2 step is', shoplist[::2])
30print('3 step is', shoplist[::3])
31# 超过步长则只返回第一个项目
32print('4 step is', shoplist[::4])
33
34# 从字符串中切片
35print('\n\nCharacters 1 to 3 is', name[1:3])
36print('Characters 2 to end is', name[2:])
37print('Characters 1 to -1 is', name[1:-1])
38print('Characters start to end is', name[:])
输出:
1Item 0 is apple
2Item 1 is mango
3Item 2 is carrot
4Item 3 is banana
5Item -1 is banana
6Item -2 is carrot
7Item -3 is mango
8Item -4 is apple
9Character 0 is S
10Item 1 to 3 is ['mango', 'carrot']
11Item 2 to end is ['carrot', 'banana']
12Item 1 to -1 is ['mango', 'carrot']
13Item start to end is ['apple', 'mango', 'carrot', 'banana']
14Item start to -1 is ['apple', 'mango', 'carrot']
15
16Item start to end is ['apple', 'mango', 'carrot', 'banana']
172 step is ['apple', 'carrot']
183 step is ['apple', 'banana']
194 step is ['apple']
20
21
22Characters 1 to 3 is wa
23Characters 2 to end is aroop
24Characters 1 to -1 is waroo
25Characters start to end is Swaroop
1>>> shoplist = ['apple', 'mango', 'carrot', 'banana']
2>>> shoplist[::1]
3['apple', 'mango', 'carrot', 'banana']
4>>> shoplist[::2]
5['apple', 'carrot']
6>>> shoplist[::3]
7['apple', 'banana']
8>>> shoplist[::-1]
9['banana', 'carrot', 'mango', 'apple']
你会注意到当步长为 2 时,我们得到的是第 0、2、4…… 位项目。当步长为 3 时,我们得到的是第 0、3……位项目。
. 集合
集合(Set)是简单对象的无序集合(Collection)。当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合。
通过使用集合,你可以测试某些对象的资格或情况,检查它们是否是其它集合的子集,找到两个集合的交集,等等。
1bri = set(['brazil', 'russia', 'india'])
2if 'india' in bri:
3 print('ths set is', bri) # 按照字符串长度自动排序
4
5print( 'india' in bri)
6print( 'china' in bri)
7
8bric = bri.copy()
9bric.add('usa')
10print('ths new_set is', bric)
11print( bric.issuperset(bri))
12
13bri.remove('russia')
14print(bri&bric ) #与操作取交集
1ths set is {'india', 'brazil', 'russia'}
2True
3False
4ths new_set is {'india', 'brazil', 'russia', 'usa'}
5True
6{'india', 'brazil'}
这个案例几乎不言自明,因为它涉及的是学校所教授的数学里的基础集合知识。
. 引用
当你创建了一个对象并将其分配给某个变量时,变量只会查阅(Refer)某个对象,并且它也不会代表对象本身。也就是说,变量名只是指向你计算机内存中存储了相应对象的那一部分。这叫作将名称绑定(Binding)给那一个对象。
案例(保存为 ds_reference.py
):
1"""
2拷贝和别名不是同一个东西
3你要记住如果你希望创建一份诸如序列等复杂对象的副本(而非整数这种简单的对象 (Object)),
4你必须使用切片操作来制作副本。如果你仅仅是将一个变量名赋予给另一个名 称,那么它们都将“查阅”同一个对象
5"""
6print('Simple Assignment')
7shoplist = ['apple', 'mango', 'carrot', 'banana']
8# mylist 只是指向同一对象的另一种名称
9mylist = shoplist
10# 我购买了第一项项目,所以我将其从列表中删除
11del shoplist[0]
12#del mylist[0]
13print('shoplist is', shoplist)
14print('mylist is', mylist)
15# 注意到 shoplist 和 mylist 二者都
16# 打印出了其中都没有 apple 的同样的列表,以此我们确认
17# 它们指向的是同一个对象
18print('Copy by making a full slice')
19# 通过生成一份完整的切片制作一份列表的副本
20mylist = shoplist[:]
21# 删除第一个项目
22del mylist[0]
23print('shoplist is', shoplist)
24print('mylist is', mylist)
25# 注意到现在两份列表已出现不同
26
27"""
28运行结果:
29Simple Assignment
30shoplist is ['mango', 'carrot', 'banana']
31mylist is ['mango', 'carrot', 'banana']
32Copy by making a full slice
33shoplist is ['mango', 'carrot', 'banana']
34mylist is ['carrot', 'banana']
35"""
36
. 有关字符串的更多内容 {#more-strings}
你在程序中使用的所有字符串都是 str
类下的对象。下面的案例将演示这种类之下一些有用的方法。要想获得这些方法的完成清单,你可以查阅 help(str)
。
案例(保存为 ds_str_methods.py
):
1name = 'Swaroop'
2# startswith 方法用于查找字符串是 否以给定的字符串内容开头
3if name.startswith('Swa'):
4 print('yes, the string starts with "Swa"')
5
6if 'a' in name:
7 print('yes, it contains the string "a"')
8
9# find 方法用于定位字符串中给定的子字符串的位置
10if name.find('war') != -1:
11 print('Yes, it contains the string "war"')
12
13if name.find(name[1:4]) != -1:
14 print('Yes, it contains the string ', name[1:4])
15
16# str 类同样还拥有一个简洁的方法用以 联结(Join) 序列(list也是一种序列)中的项目
17delimiter = '_*_'
18mylist = ['Brazil', 'Russia', 'India', 'China']
19print(delimiter.join(mylist))
输出:
1yes, the string starts with "Swa"
2yes, it contains the string "a"
3Yes, it contains the string "war"
4Yes, it contains the string war
5Brazil_*_Russia_*_India_*_China
. 总结
我们已经详细探讨了 Python 中内置的多种不同的数据结构。这些数据结构对于编写大小适中的 Python 程序而言至关重要。
现在我们已经具备了诸多有关 Python 的基本知识,接下来我们将会了解如何设计并编写一款真实的 Python 程序。
更多请扫码关注: