python中list列表的高级函数
|
在Python所有的数据结构中,list具有重要地位,并且非常的方便,这篇文章主要是讲解list列表的高级应用,基础知识可以查看博客。 use a list as a stack: #像栈一样使用列表 stack = [3,4,5] stack.append(6) stack.append(7) stack [3,5,6,7] stack.pop() #删除最后一个对象 7 stack [3,6] stack.pop() 6 stack.pop() 5 stack [3,4] use a list as a queue: #像队列一样使用列表
> from collections import deque #这里需要使用模块deque
> queue = deque(["Eric","John","Michael"])
> queue.append("Terry") # Terry arrives
> queue.append("Graham") # Graham arrives
> queue.popleft() # The first to arrive now leaves
'Eric'
> queue.popleft() # The second to arrive now leaves
'John'
> queue # Remaining queue in order of arrival
deque(['Michael','Terry','Graham'])
three built-in functions: 三个重要的内建函数 filter(),map(),and reduce(). > def f(x): return x % 3 == 0 or x % 5 == 0 ... #f函数为定义整数对象x,x性质为是3或5的倍数 > filter(f,range(2,25)) #筛选 [3,9,10,12,15,18,20,21,24] 2)、map(function,sequence): > def cube(x): return x*x*x #这里是立方计算 还可以使用 x**3的方法 ... > map(cube,range(1,11)) #对列表的每个对象进行立方计算 [1,8,27,64,125,216,343,512,729,1000] 注意:这里的参数列表不是固定不变的,主要看自定义函数的参数个数,map函数可以变形为:def func(x,y) map(func,sequence1,sequence2) 举例: seq = range(8) #定义一个列表 > def add(x,y): return x+y #自定义函数,有两个形参 ... > map(add,seq,seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误 [0,2,14] 3)、reduce(function,sequence): def add(x,y): return x+y ... reduce(add,11)) 55 List comprehensions: Nested List Comprehensions: matrix = [ #此处定义一个矩阵 ... [1,3,4],... [5,7,8],... [9,11,12],... ] [[row[i] for row in matrix] for i in range(4)] #[[1,9],[2,10],[3,11],[4,12]] 这里两层嵌套比较麻烦,简单讲解一下:对矩阵matrix,for row in matrix来取出矩阵的每一行,row[i]为取出每行列表中的第i个(下标),生成一个列表,然后i又是来源于for i in range(4) 这样就生成了一个列表的列表。 The del statement: > a = [-1,66.25,333,1234.5] >del a[0] #删除下标为0的元素 >a [1,1234.5] >del a[2:4] #从列表中删除下标为2,3的元素 >a [1,1234.5] >del a[:] #全部删除 效果同 del a >a [] Sets: 集合
> basket = ['apple','orange','apple','pear','banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange','banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a','r','b','c','d'])
>>> a - b # letters in a but not in b
set(['r','d','b'])
>>> a | b # letters in either a or b
set(['a','m','z','l'])
>>> a & b # letters in both a and b
set(['a','c'])
>>> a ^ b # letters in a or b but not both
set(['r','l'])
Dictionaries:字典
>>> tel = {'jack': 4098,'sape': 4139}
>>> tel['guido'] = 4127 #相当于向字典中添加数据
>>> tel
{'sape': 4139,'guido': 4127,'jack': 4098}
>>> tel['jack'] #取数据
4098
>>> del tel['sape'] #删除数据
>>> tel['irv'] = 4127 #修改数据
>>> tel
{'guido': 4127,'irv': 4127,'jack': 4098}
>>> tel.keys() #取字典的所有key值
['guido','irv','jack']
>>> 'guido' in tel #判断元素的key是否在字典中
True
>>> tel.get('irv') #取数据
4127
也可以使用规则生成字典:
>>> {x: x**2 for x in (2,6)}
{2: 4,4: 16,6: 36}
enumerate():遍历元素及下标 >>> for i,v in enumerate(['tic','tac','toe']): ... print i,v ... 0 tic 1 tac 2 toe zip():
>>> questions = ['name','quest','favorite color']
>>> answers = ['lancelot','the holy grail','blue']
>>> for q,a in zip(questions,answers):
... print 'What is your {0}? It is {1}.'.format(q,a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
有关zip举一个简单点儿的例子: >>> a = [1,3] >>> b = [4,6] >>> c = [4,8] >>> zipped = zip(a,b) [(1,5),6)] >>> zip(a,c) [(1,6)] >>> zip(*zipped) [(1,(4,6)] reversed():反转 >>> for i in reversed(xrange(1,2)): ... print i ... sorted(): 排序 > basket = ['apple','banana'] > for f in sorted(set(basket)): #这里使用了set函数 ... print f ... apple banana orange pear python的set和其他语言类似,是一个 基本功能包括关系测试和消除重复元素. To change a sequence you are iterating over while inside the loop (for example to duplicate certain items),it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient: >>> words = ['cat','window','defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0,w) ... >>> words ['defenestrate','cat','defenestrate'] 以上就是本文的全部内容,希望对大家的学习有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
