在python所有的数据结构中,list具有重要地位,并且非常的方便,这篇文章主要是讲解list列表的高级应用,基础知识可以查看博客。
此文章为python英文文档的翻译版本,你也可以查看英文版。https://docs.python.org/2/tutorial/datastructures.html
use a list as a stack: #像栈一样使用列表
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]
use a list as a queue: #像队列一样使用列表
| 12345678910 | > 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 arrivaldeque([\’Michael\’, \’Terry\’, \’Graham\’]) |
three built-in functions: 三个重要的内建函数
filter(), map(), and reduce().
filter(function, sequence)::
按照function函数的规则在列表sequence中筛选数据
| 1234 | > def f(x): return x % 3 == 0 or x % 5 == 0... #f函数为定义整数对象x,x性质为是3或5的倍数> filter(f, range(2, 25)) #筛选[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24] |
map(function, sequence):
map函数实现按照function函数的规则对列表sequence做同样的处理,
这里sequence不局限于列表,元组同样也可。
| 1234 | > 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) 举例:
| 12345 | seq = range(8) #定义一个列表> def add(x, y): return x+y #自定义函数,有两个形参...> map(add, seq, seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误[0, 2, 4, 6, 8, 10, 12, 14] |
reduce(function, sequence):
reduce函数功能是将sequence中数据,按照function函数操作,如 将列表第一个数与第二个数进行function操作,得到的结果和列表中下一个数据进行function操作,一直循环下去…
举例:
| 1234 | def add(x,y): return x+y...reduce(add, range(1, 11))55 |
List comprehensions:
这里将介绍列表的几个应用:
squares = [x**2 for x in range(10)]
#生成一个列表,列表是由列表range(10)生成的列表经过平方计算后的结果。
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != 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。
Nested List Comprehensions:
这里比较难翻译,就举例说明一下吧:
| 1234567 | matrixn-num crayon-striped-num\” data-line=\”crayon-5812b07328ed7210962052-6\”>67 | matrix\”>https://docs.python.org/2/tutorial/datastructures.html
use a list as a stack: #像栈一样使用列表
use a list as a queue: #像队列一样使用列表
three built-in functions: 三个重要的内建函数 filter(), map(), and reduce().
map(function, sequence):
注意:这里的参数列表不是固定不变的,主要看自定义函数的参数个数,map函数可以变形为:def func(x,y) map(func,sequence1,sequence2) 举例:
reduce(function, sequence):
List comprehensions: Nested List Comprehensions:
|