python中list列表的高级函数
在Python所有的数据结构中,list具有重要地位,并且非常的方便,这篇文章主要是讲解list列表的高级应用,基础知识可以查看博客。
此文章为python英文文档的翻译版本,你也可以查看英文版:https://docs.python.org/2/tutorial/datastructures.html
usealistasastack:#像栈一样使用列表
stack=[3,4,5] stack.append(6) stack.append(7) stack [3,4,5,6,7] stack.pop()#删除最后一个对象 7 stack [3,4,5,6] stack.pop() 6 stack.pop() 5 stack [3,4]
usealistasaqueue:#像队列一样使用列表
>fromcollectionsimportdeque#这里需要使用模块deque
>queue=deque(["Eric","John","Michael"])
>queue.append("Terry")#Terryarrives
>queue.append("Graham")#Grahamarrives
>queue.popleft()#Thefirsttoarrivenowleaves
'Eric'
>queue.popleft()#Thesecondtoarrivenowleaves
'John'
>queue#Remainingqueueinorderofarrival
deque(['Michael','Terry','Graham'])
threebuilt-infunctions:三个重要的内建函数
filter(),map(),andreduce().
1)、filter(function,sequence)::
按照function函数的规则在列表sequence中筛选数据
>deff(x):returnx%3==0orx%5==0 ...#f函数为定义整数对象x,x性质为是3或5的倍数 >filter(f,range(2,25))#筛选 [3,5,6,9,10,12,15,18,20,21,24]
2)、map(function,sequence):
map函数实现按照function函数的规则对列表sequence做同样的处理,
这里sequence不局限于列表,元组同样也可。
>defcube(x):returnx*x*x#这里是立方计算还可以使用x**3的方法 ... >map(cube,range(1,11))#对列表的每个对象进行立方计算 [1,8,27,64,125,216,343,512,729,1000]
注意:这里的参数列表不是固定不变的,主要看自定义函数的参数个数,map函数可以变形为:deffunc(x,y)map(func,sequence1,sequence2)举例:
seq=range(8)#定义一个列表 >defadd(x,y):returnx+y#自定义函数,有两个形参 ... >map(add,seq,seq)#使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误 [0,2,4,6,8,10,12,14]
3)、reduce(function,sequence):
reduce函数功能是将sequence中数据,按照function函数操作,如将列表第一个数与第二个数进行function操作,得到的结果和列表中下一个数据进行function操作,一直循环下去…
举例:
defadd(x,y):returnx+y ... reduce(add,range(1,11)) 55
Listcomprehensions:
这里将介绍列表的几个应用:
squares=[x**2forxinrange(10)]
#生成一个列表,列表是由列表range(10)生成的列表经过平方计算后的结果。
[(x,y)forxin[1,2,3]foryin[3,1,4]ifx!=y]
#[(1,3),(1,4),(2,3),(2,1),(2,4),(3,1),(3,4)]这里是生成了一个列表,列表的每一项为元组,每个元组是由x和y组成,x是由列表[1,2,3]提供,y来源于[3,1,4],并且满足法则x!=y。
NestedListComprehensions:
这里比较难翻译,就举例说明一下吧:
matrix=[#此处定义一个矩阵 ...[1,2,3,4], ...[5,6,7,8], ...[9,10,11,12], ...] [[row[i]forrowinmatrix]foriinrange(4)] #[[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
这里两层嵌套比较麻烦,简单讲解一下:对矩阵matrix,forrowinmatrix来取出矩阵的每一行,row[i]为取出每行列表中的第i个(下标),生成一个列表,然后i又是来源于foriinrange(4)这样就生成了一个列表的列表。
Thedelstatement:
删除列表指定数据,举例:
>a=[-1,1,66.25,333,333,1234.5] >dela[0]#删除下标为0的元素 >a [1,66.25,333,333,1234.5] >dela[2:4]#从列表中删除下标为2,3的元素 >a [1,66.25,1234.5] >dela[:]#全部删除效果同dela >a []
Sets:集合
>basket=['apple','orange','apple','pear','orange','banana']
>>>fruit=set(basket)#createasetwithoutduplicates
>>>fruit
set(['orange','pear','apple','banana'])
>>>'orange'infruit#fastmembershiptesting
True
>>>'crabgrass'infruit
False
>>>#Demonstratesetoperationsonuniquelettersfromtwowords
...
>>>a=set('abracadabra')
>>>b=set('alacazam')
>>>a#uniquelettersina
set(['a','r','b','c','d'])
>>>a-b#lettersinabutnotinb
set(['r','d','b'])
>>>a|b#lettersineitheraorb
set(['a','c','r','d','b','m','z','l'])
>>>a&b#lettersinbothaandb
set(['a','c'])
>>>a^b#lettersinaorbbutnotboth
set(['r','d','b','m','z','l'])
Dictionaries:字典
>>>tel={'jack':4098,'sape':4139}
>>>tel['guido']=4127#相当于向字典中添加数据
>>>tel
{'sape':4139,'guido':4127,'jack':4098}
>>>tel['jack']#取数据
4098
>>>deltel['sape']#删除数据
>>>tel['irv']=4127#修改数据
>>>tel
{'guido':4127,'irv':4127,'jack':4098}
>>>tel.keys()#取字典的所有key值
['guido','irv','jack']
>>>'guido'intel#判断元素的key是否在字典中
True
>>>tel.get('irv')#取数据
4127
也可以使用规则生成字典:
>>>{x:x**2forxin(2,4,6)}
{2:4,4:16,6:36}
enumerate():遍历元素及下标
enumerate函数用于遍历序列中的元素以及它们的下标:
>>>fori,vinenumerate(['tic','tac','toe']): ...printi,v ... 0tic 1tac 2toe
zip():
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将listunzip(解压)。
>>>questions=['name','quest','favoritecolor']
>>>answers=['lancelot','theholygrail','blue']
>>>forq,ainzip(questions,answers):
...print'Whatisyour{0}?Itis{1}.'.format(q,a)
...
Whatisyourname?Itislancelot.
Whatisyourquest?Itistheholygrail.
Whatisyourfavoritecolor?Itisblue.
有关zip举一个简单点儿的例子:
>>>a=[1,2,3] >>>b=[4,5,6] >>>c=[4,5,6,7,8] >>>zipped=zip(a,b) [(1,4),(2,5),(3,6)] >>>zip(a,c) [(1,4),(2,5),(3,6)] >>>zip(*zipped) [(1,2,3),(4,5,6)]
reversed():反转
>>>foriinreversed(xrange(1,10,2)): ...printi ...
sorted():排序
>basket=['apple','orange','apple','pear','orange','banana'] >forfinsorted(set(basket)):#这里使用了set函数 ...printf ... apple banana orange pear
python的set和其他语言类似,是一个基本功能包括关系测试和消除重复元素.
Tochangeasequenceyouareiteratingoverwhileinsidetheloop(forexampletoduplicatecertainitems),itisrecommendedthatyoufirstmakeacopy.Loopingoverasequencedoesnotimplicitlymakeacopy.Theslicenotationmakesthisespeciallyconvenient:
>>>words=['cat','window','defenestrate'] >>>forwinwords[:]:#Loopoveraslicecopyoftheentirelist. ...iflen(w)>6: ...words.insert(0,w) ... >>>words ['defenestrate','cat','window','defenestrate']
以上就是本文的全部内容,希望对大家的学习有所帮助。