【python】python数据结构

来源:互联网 发布:淘宝有多少买家注册 编辑:程序博客网 时间:2024/06/03 22:40

1、数据结构,就是存储一组相关的数据。或者说,处理一些数据的结构。

python有4种内建的数据结构:列表、元组、字典、集合。

2、列表:

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

列表中的项目应该包含在方括号内。这样python就知道你是在指明一个列表。一旦你建立了一个列表,你可以添加、删除或者搜索列表中的项目。由于可添加或者删除,所以,列表是一个可变的数据类型。

3、对象和类

列表就是使用了对象和类的例子。

当我们对变量 x 赋值5,就是,创建了一个类int的对象(即实例)x。

一个类也可以有方法(即函数)来使用,当然,必须首先定义该类的对象(函数)。

python给列表提供了可以在列表末尾增加项目的方法append。如mylist.append('my my')会给列表增加一个字符串。

类也有字段,就是对类而言,定义了变量来使用。当有一个该类的对象的时候,你可以使用这些名字或变量。字段也可以用点来访问。

---------------

#C:/Python33/HwhCode#Filename: class.py#This is my shopping listshoplist= ['apple','mango','carrot','banana']print('I have',len(shoplist),'item to purchase.')print('These item 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)

--------------


解析:

(1)shoplist是一个购物单,其中存储了各项要买的物品的名字,同时也可以增加任意类型的对象,包括数字,甚至列表。

(2)使用for...in...循环,遍历列表中的各项来进行重复。所以,列表也是一个序列。

(3)print函数的end参数,表示以空格结束输出。而不是通常的换行。

(4)append方法来给列表中增加一项。然后通过将列表简单的传递给print语句,就能漂亮的输出列表。

(5)sort方法进行排序。

(6)我们买完了一项物品,想要将其从列表中移除。用del语句来实现。

(7)help(list)获取列表的众多解释。

4、元组

(1)元组用来将多样的对象集合到一起。元组和列表十分类似。只不过元组和字符串一样是不可变的。

(2)元组通过圆括号中用逗号分隔的项目定义。

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

---------------------

#C:\Python33\CodeHwh#using_tuple.pyzoo = ('python','elephant','penguin') #remember the parenteses are optionalprint('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 zoo is',len(new_zoo)-1+len(new_zoo[2]))

----------------


知识点解析:

(1)变量zoo是一个元组,使用len函数可以获取这个元组的长度。这表明元组也是一个序列。

(2)由于老动物园关闭了,我们把动物转移到新动物园,因此,new_zoo元组包含了一些一些新动物和从老动物园带过来的动物。元组之内的元组不会失去它的特性。

(3)我们通过一对方括号,来指明某个项目的位置,从而访问元组中的项目。这跟列表的用法一样。称为索引运算符。new_zoo[2]来访问new_zoo的第三个项目。而new_zoo[2][2]来访问new_zoo元组的第三个项目的第三个项目。

(4)圆括号是用来区分元组的,比如print(1,2,3)与print((1,2,3))是不一样的,前者打印三个数字,后者打印一个元组,这个元组包含三个数字。

(5)一个空的元组由一堆空的圆括号组成,如mycmpty = ()。然而,含有单个元素的元组必须在第一个项目的后面跟一个逗号,虽然它没有第二个元素。只有这样,python才能区分表达式中一个元组和一个带括号的对象。即表示为:mycmpty1 = (1,)。

5、字典

(1)字典类似于你通过来联系人名字查找地址和联系人详细情况的地址薄,即,我们把键(名字)和值(详细情况)联系在一起。注意,键,必须是唯一的,就像如果有两个人同名,就无法找到正确的信息。

(2)只能使用不可变的对象(比如字符串)作为字典的键。但可以把不可变的或者可变的对象作为字典的值。就是说,应该只使用简单的对象作为键。

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

(4)字典中的键/值对是没有顺序的。如果想要一个特定的顺序,就应该在使用前对它们排序。

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

--------------

#######using_dict#########'ab' is short for 'a'ddress'b'ookab = {'Swaroop':'swaroop@swaroopch.com',      'Larry':'larry@wall.org',      'Matsumoto':'matz@ruby-lang.org',      'Spammer':'spammer@hotmail.com'    }print("Swaroop's address is",ab['Swaroop'])#Deleting a key-value pairdel ab['Spammer']print('\nThere are {0} contacts in the address-book\n'.format(len(ab)))for name, address in ab.items():    print('Contact {0} at {1}'.format(name,address))#Adding a key-value pairab['Guido'] = 'guido@python.org'if 'Guido' in ab:#OR ab.has_key('Guido')    print("\nGuido's address is",ab['Guido'])

---------------


(1)我们使用已经介绍过的标记创建了字典ab,然后我们使用索引操作符来指定键,从而使用键值对。

(2)使用索引操作符来寻找一个键,并为它赋值,这样就增加了一个新的键值对,就像Guido一样。

(3)使用del来删除键值对。

(4)items是字典的方法,来使用字典中的每个键值对。这会返回一个元组的列表。其中每个元组都包含一对项目:键和值。我们抓取这个对,然后赋给for...in...循环的两个变量:name和address。然后在for中一块打印这些值。

(5)我们可以使用in操作符来检验一个键值对是否存在。或者用字典的has_key方法。

(6)help(dict)查看dict类的完整方法。

6、序列:

(1)列表、元组和字符串都是序列。

(2)序列的主要特点是:索成员检验(在和不在表达式中)和索引操作符(直接从序列中抓取一个特定的项目)。

(3)序列也有切片操作,让我们取出序列的薄片。

-------------

#C:/python33/HwhCode#seq.pyshoplist = ['apple','mango','carrot','banana']name = 'swaroop'# Indexing or 'Subscription' operationprint('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])print('Character 0 is',name[0])#Slicing on a listprint('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[:])
--------------


(1)首先用索引来取得序列中单个项目。即,下标操作。每当你用方括号中的一个数来指定一个序列的时候,python会抓取序列中对应位置的一个项目。python从0开始计数。

(2)索引同样可以是负数。位置是从序列尾部开始计数。shoplist[-1]表示最后一个项目。shoplist[-2]表示倒数第二个项目。

(3)切片操作符,是序列名后跟一个方括号,方括号内有一组可选数字,并用冒号分隔。数字是可选的,冒号是必须的。

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

例如:shoplist[1:3]返回从位置1开始,包括位置2,但是终止在位置3的一个序列切片。所以,返回一个含有两个项目的切片。

shoplist[:]返回整个序列的拷贝。

(5)可以用负数做切片,负数用在从序列尾部开始计算的位置,shoplist[:-1]会返回除了最后一个项目外,包含所有项目的序列切片。

(6)可以给切片规定第三个参数,即切片的步长。默认步长为1。

------------

#C:/python33/HwhCode#seq.pyshoplist = ['apple','mango','carrot','banana']name = 'swaroop'# Indexing or 'Subscription' operationprint('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])print('Character 0 is',name[0])#Slicing on a listprint('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('Item start to end is',shoplist[::1])print('Item start to end is',shoplist[::2])print('Item start to end is',shoplist[::3])print('Item start to end is',shoplist[::-1])
---------------


当步长为2时,我们得到了位置为0,2的项,当步长为3时,我们得到了步长为0,3的项。

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

7、集合

(1)集合是没有顺序的简单的对象的聚集。当在聚集中的一个对象的存在比其顺序或者出现的次数重要时,使用集合。

(2)使用集合,可以检查是否是成员。是否是另一个集合的子集,得到两个集合的交集。

-------

#########bri = set(['brazil','russia','india'])print('india' in bri)print('usa' in bri)bric = bri.copy()bric.add('china')print(bric.issuperset(bri))bri.remove('russia') #OR bri.intersection(bric)print(bri & bric)
-----


8、引用

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


-----------

####reference####print('Simple Assignment')shoplist = ['apple','mango','carrot','banana']mylist = shoplist #mylist is just another name point to the same listdel shoplist[0] #I purchased the first item, so I remove it from the listprint('shoplist is',shoplist)print('mylist is',mylist)#notice that both shoplist and mylist both print the same list whithout# the 'apple' confirming that they point to the same objectprint('Copy by making a full slice')mylist = shoplist[:] #make a copy by doing a full slicedel mylist[0] #remove first itemprint('shoplist is',shoplist)print('mylist is',mylist)
-------------


解析:

(1)如果你想要复制一个列表,或者类似的序列,或者其他复杂的对象(不是如整数那样的简单对象),那么你必须使用切片操作符来获得拷贝。如果你只是想用另外一个变量名,两个名称都引用同一个对象,要小心。

(2)列表的赋值语句不创建拷贝,得使用切片操作符来建立拷贝序列。

9、字符串:

(1)在程序中使用的字符串,都是str类的对象。

-------

#C:/python33/HwhCode#####str_methods####name = 'Swaroop' # This is a string objectif 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))
---------


知识点:

(1)我们看到了许多字符串的方法,startswith是用来测试字符串是否以给定字符串开始的。

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

(3)find方法用来找出给定字符串在另一个字符串中的位置。如果返回-1,表示没有找到子字符串。str类也有以一个作为分隔符的字符串join序列的项目的整洁方法,它返回一个生成的大字符串。


原创粉丝点击