码迷,mamicode.com
首页 > 编程语言 > 详细

python 2.7 中文教程及自动化测试介绍(3) -- 待整理

时间:2015-09-19 16:53:36      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

数据结构


本章详细讨论一些已学知识,并引入了一些新知识。
列表的详细介绍

列表的所有方法如下:

    list.append(x):附加元素到列表末端,相当于a[len(a):] = [x]。
    list.extend(L):附加列表L的内容到当前列表后面,相当于 a[len(a):] = L 。
    list.insert(i, x):在指定位置i插入x。i表示插入位置,原来的i位置如果有元素则往后移动一个位置,例如 a.insert(0, x)会插入到列表首部,而a.insert(len(a), x)相当于a.append(x)。
    list.remove(x):删除列表中第一个值为x的元素。如果没有就报错。
    list.pop([i]):产出列表指定位置的元素,并将其返回该元素。如果没有指定索引针对最后一个元素。方括号表示i是可选的。
    list.index(x):返回第一个值为x的元素的索引。如果没有则报错。
    list.count(x):返回x在列表中出现的次数。
    list.sort(cmp=None, key=None, reverse=False):就地对链表中的元素进行排序。
    list.reverse():就地反转元素。

实例:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count(‘x‘)
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333, 333]

把链表当作堆栈使用

堆栈后进先出。进使用append(),出使用pop()。例如:

>>> 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]

把列表当作队列使用

列表先进先出。列表头部插入或者删除元素的效率并不高,因为其他相关元素需要移动,建议使用collections.deque。

>>> from collections import 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‘])

函数式编程工具

对于列表来讲,有三个内置函数非常有用: filter(), map(), 以及reduce()。

filter(function, sequence)返回function(item)为true的子序列。会尽量返回和sequence相同的类型)。sequence是string或者tuple时返回相同类型,其他情况返回list 。实例:返回不能被2和3整除的整数:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

map(function, sequence) 为每个元素调用 function(item),并将返回值组成一个列表返回。例如计算立方:

>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

PyAutoGUI

参考资料


python 2.7 中文教程及自动化测试介绍(3) -- 待整理

标签:

原文地址:http://my.oschina.net/u/1433482/blog/508525

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!