python学习---第十六天

来源:互联网 发布:himall2.6官方版源码 编辑:程序博客网 时间:2024/06/05 12:49

在下这厢有礼了

学一门语言,最基础和重要的就是数据结构了,而在python中最基本的数据结构是序列,也可以理解为数组,但貌似比数组强大。

>>> jason=['jason',42]>>> james=['james',45]>>> database=[jason,james]>>> database[['jason', 42], ['james', 45]]>>> 

索引:

>>> greeting='hello'>>> greeting[0]'h'>>> greeting[-1]  ==>反着的时候从-1而不是0开始开始'o'>>> digital=raw_input ("year:")[3]year:2013>>> digital'3'

索引实例:

>>> months=['January','February','March','April',\    'May','June','July','August','September','October'\    'November','December']   #根据指定的年月日以数字形式打印出日期>>> endings=['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st'] #以1-31的数字作为结尾的列表>>> year=raw_input ("Year:")Year:2013>>> month=raw_input('Month(1-12):')Month(1-12):3>>> day=raw_input('Day(1-31):')Day(1-31):30>>> month_num=int(month)>>> day_num=int(day)>>> month_name=months[month_num-1]   ==>注意这里索引要减1>>> ordinal=day+endings[day_num-1]>>> print month_name +' '+ordinal + ', '+ yearMarch 30th, 2013>>> 

分片:

使用索引能访问单个元素,使用分片能访问一定范围的元素,分片通过冒号相隔的两个索引来实现。

>>> tag='<a href="http://www.python.org">Python web site</a>'>>> tag[9:30]'http://www.python.org'>>> tag[32:-4]'Python web site'>>>

>>> numbers=[1,2,3,4,5,6,7,8,9,10]>>> numbers[3:6][4, 5, 6]>>> numbers[-3:-1][8, 9]>>> numbers[-3:0]  #分片中的最左边的索引比它右边索引的晚出现在序列中,结果就是一个空序列[]>>> numbers[-3:] #默认到最后[8, 9, 10]>>> numbers[:3] #默认从第一个开始[1, 2, 3]>>> numbers[:]   #默认全部[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

很显然,分片操作的实现需要提供两个索引作为边界,第一个索引的元素包含在分片内,而第二个不包含在分片内

分片步长:默认步长没有写,是1,分片格式:上边界:下边界:步长
>>> numbers[0:10:1]  #默认步长是1[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> numbers[0:10:2]   #步长设为2[1, 3, 5, 7, 9]>>> numbers[3:6:3]   #步长设为3[4]>>> numbers[::4]  [1, 5, 9]
>>> [1,2,3]+[4,5,6][1, 2, 3, 4, 5, 6]>>> [1,2,3]+'world'   #列表和字符串都是序列,但是不能连在一起,两种同类型的序列才能进行连接操作Traceback (most recent call last):  File "<pyshell#141>", line 1, in <module>    [1,2,3]+'world'TypeError: can only concatenate list (not "str") to list>>> 

>>> numbers[8:3:-1] #步长不能为0,因为不会向下执行,可以为负数,向前执行[9, 8, 7, 6, 5]>>> numbers[10:0:-2] #当步长为负数时,开始索引必须大于结束索引[10, 8, 6, 4, 2]>>> numbers[0:10:-2][]>>> numbers[::-2][10, 8, 6, 4, 2]>>> numbers [5::-2][6, 4, 2]>>> numbers[:5:-2][10, 8]>>>
序列相加:

空列表可以简单的通过[ ]表示,但若想要创建一个占用十个元素空间,却不包括任何有用的有用的内容列表。这时需要使用None,None是Python的内建值,初始化一个长度为10的列表如下:

>>> sequence=[None]*10>>> sequence[None, None, None, None, None, None, None, None, None, None]


序列乘法示例:(存在脚本中运行)
sentence=raw_input ("Sentence:")screen_width=60text_width=len(sentence)box_width=text_width+6left_margin=(screen_width-box_width)//2printprint ' ' * left_margin + '+' + '-' * (box_width-2)  + '+'print ' ' * left_margin + '|   ' + ' ' * text_width  +' |'print ' ' * left_margin + '|   ' +          sentence +' |'print ' ' * left_margin + '|   ' + ' ' * text_width  +' |'print ' ' * left_margin + '+' + '-' * (box_width-2)  + '+'printraw_input()
in运算符:检查一个值是否在序列中
database=[['jason','42'],['james','45'],['jzhou','22']]username=raw_input("Username:")age=raw_input("Age:")if [username,age] in database:    print "OK,right"raw_input()


序列成员资格示例:
>>> permission='rwx'   #有木有觉得这个像判断Linux中某个文件的执行权限,确实可以这么判断>>> 'w' in permissionTrue>>> 'xx' in permissionFalse>>> users=['jason','james','jzhou']>>> raw_input ("enter your name:") in usersenter your name:jzhouTrue


内建函数len、min、max


>>> numbers[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> len(numbers)10>>> max(numbers)10>>> min(numbers)1>>> 


列表

 列表不同于元组和字符串,列表是可变的,而且列表有许多专门的方法。字符串不能像列表一样被修改,但是列表中的list函数可以实现修改。列表的常用用法:

>>> list('hello')['h', 'e', 'l', 'l', 'o']>>> x=[1,1,1]>>> x[1]=2    #可以改变列表为元素赋值>>> x[2]=3>>> x[1, 2, 3]>>> names=['james','jason','jzhou','liwear']  #可以删除列表中的元素>>> del names[3]>>> names['james', 'jason', 'jzhou']>>> name=list('jzhou')>>> name
sorted函数可以用于任何序列,却总是返回一个列表:>>> sorted("Python")   #默认按ASCII码排序['P', 'h', 'n', 'o', 't', 'y']

>>> cmp(42,23)>>> cmp(99,100)-1>>> cmp(1,1)>>> numbers=[5,2,6,7]>>> numbers.sort(cmp)    #这个机制之后会介绍>>> numbers[2, 5, 6, 7]

['j', 'z', 'h', 'o', 'u']>>> name[2:]=list('1314') #可以分片赋值>>> name['j', 'z', '1', '3', '1', '4']
>>> numbers=[1,5]  #分片赋值可以在不需要替换任何元素的情况下插入新元素>>> numbers[1:1]=[2,3,4]>>> numbers[1, 2, 3, 4, 5]>>> numbers[1:4]=[]  #也可以变相的删除元素>>> numbers[1, 5]


列表的方法主要有append, count,extend,index,insert,pop,remove,reverse,sort,简单用法如下:
>>> list=[1,2,3] >>> list .append(4)  # append用于在列表末尾追加新对象 >>> list [1, 2, 3, 4]>>> ['to','be','or','to'].count('to')  #count用于统计某个元素在列表中出现的次数>>> x=[[1,2],1,1,[2,1,[1,2]]]>>> x.count(1)>>> x.count([1,2])>>> a=[1,2,3]>>> b=[4,5,6]>>> a.extend(b)   #extend在列表的末尾一次性追加另一个序列的多个值,扩展原有列表>>> a[1, 2, 3, 4, 5, 6]   #注意这个操作与连接操作不同,extend修改了被扩展的序列即a,而连接只是临时显示并没有变>>> a=[1,2,3]>>> b=[4,5,6]>>> a[len(a):]=b   #也可以通过分片赋值来扩展,但是可读性不强>>> a[1, 2, 3, 4, 5, 6]>>> sentence=['we','are','good','student']>>> sentence.index ('are')    #index用于从列表中找出某个值第一个匹配项的索引位置>>> numbers=[1,2,3,4,5,6,7]>>> numbers.insert(3,'four')  #insert用于将对象插入列表中,和数据结构中的链表操作非常相似>>> numbers[1, 2, 3, 'four', 4, 5, 6, 7]>>> numbers=[1,2,3,4,5,6,7]>>> numbers[3:3]=['four']   #也可以使用分片赋值的方法实现,但是可读性不强>>> numbers[1, 2, 3, 'four', 4, 5, 6, 7]>>> x=[1,2,3]   >>> x.pop()  #出栈操作,和数据结构中的栈操作一样,即移除列表中的最后一个,并且返回该元素的值>>> x[1, 2]>>> x.pop()>>> x=[1,2,3]>>> x.append(x.pop())   #这个操作和数据结构中的push、pop是一样的,追加刚刚出栈的值,很有趣,最后得到的还是是原来的值>>> x[1, 2, 3]>>> x=['to','be','or','not','to','be']>>> x.remove ('be')  #remove用于移除列表中某个值的第一个匹配项>>> x         #值得注意的是remove方法是没有返回值的原位置改变方法,注意和pop的区别['to', 'or', 'not', 'to', 'be']>>> x=[1,2,3]>>> x.reverse ()  #将列表中的元素反向存放,注意这种方法改变了列表但没有返回值>>> x[3, 2, 1]>>> x=[4,5,6,7,1,2,3]>>> x.sort()  #sort用于在原位置对列表进行排序,也改变了序列的值,但是没有返回值>>> x[1, 2, 3, 4, 5, 6, 7]>>>



元组——不可变序列

  元组和列表一样,也是一种序列,唯一的不同是元组不能修改,字符串也是如此;创建元素很简单,用逗号分隔一些值,就自动创建了元组:

>>> 1,2,3(1, 2, 3)>>> (1,2,3)(1, 2, 3)>>> (42,)  # 逗号说明它是一个元组,不然加括号(如:(42))也没用(42,)>>> 3*(40+2)  #这个例子说明了逗号的重要性,42和(42)是完全一样的>>> 3*(40+2,)    (42, 42, 42)>>>

tuple函数:

   tuple函数的功能与list函数基本一样:以一个序列作为参数把它转换为元组。如果参数是数组,那么该参数就会被原样返回:

>>> tuple([1,2,3])(1, 2, 3)>>> tuple('abc')('a', 'b', 'c')>>> tuple((1,2,3))(1, 2, 3)

 
用到的函数总结:cmp(x,y)、len(seq)(返回序列长度)、list(seq)(把序列转换成列表)、max(args)、min(args)、reverse(seq)(对序列进行反向迭代)、sorted(seq)(返回已排序的包含seq所有元素的列表)、tuple(seq)(把序列转换成元组)

 
原创粉丝点击