python语法初学2

5.数据结构

5.1 关于list数据类型

list.append(x) 把x加到列表尾部

list.extend(L)  把表L加到表尾,等价于a[len(a):] = L.

list.insert(I,x)  在位置i前面插入x

list.remove(x) 移除表中第一个值为x的表项

list.pop([I])   移除i表项,并返回此表项值,若没指定i,移除最后一个表项(方括号表示i可填可不填)

list.index(x)   返回表中值为x的目录

list.count(x)   返回x出现的次数

list.sort()排序

list.reverse()   反转表格

 

5.1.1把列表当作栈使用

用append和pop可轻易实现

 

5.1.2把列表当作队列使用

使用collections.deque

From collections import deque

使用queue.append(x)入队,popleft(x) 出队

 

5.1.3编程工具

filter(function, sequence) 返回序列中的值输入到函数中,函数返回为真的序列值

例子:

>>> def f(x): return x % 3 == 0 or x % 5 == 0

...

>>> filter(f, range(2, 25))

[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

map(function, sequence) 将序列值依次代入,输出函数返回值构成的列表

若函数有两个参数,可后跟两个序列,分别作为前后两个参数

>>> seq = range(8)

>>> def add(x, y): return x+y

...

>>> map(add, seq, seq)

[0, 2, 4, 6, 8, 10, 12, 14]

 

reduce(function, sequence) 序列的头两个值传入函数,得到一个返回值,然后再和第三个序列值作为两个参数传入函数,如此往复

>>> def add(x,y): return x+y

...

>>> reduce(add, range(1, 11))

55

 

A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence

 

5.1.4

 

 

猜你喜欢

转载自blog.csdn.net/sinat_30457013/article/details/89523436