标签:
这章会更详细地描述了一些你已经学过的知识,同时添加一些新东西。
下面是关于List的所有方法
>>> 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]
你可能会注意到像insert、remove或sort这样的方法只修改了List而没有返回值——其实他们都返回了空值None。这是Python中对所有可变数据结构的一个设计原则
List的方法让它很容易像Stack那样被使用,最后一个加入的元素第一个被删除("后进先出"原则 )。使用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]
>>> 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‘])
>>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
值得注意的是,我们在loop完成后创建了(甚至覆盖)一个名称为 x 的变量。实际上,我们可以通过一行的列表生成式来清晰安全地创建:
squares = list(map(lambda x: x**2, range(10)))
或是等价于:
squares = [x**2 for x in range(10)]
这无疑是更加精确和可读的。
这个列表生成式在圆括号后紧跟了一个for从句,然后是零或多个for 或if 从句。而返回结果则是计算从句中的表达式所产生的新list。例如这个返回结果包含了两个list中互不相等的元素对。
>>> [(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)]
for和if的顺序在这两段代码中是相同的。
如果返回结果是一个tuple元组,就像上例中的那样,那么必须加上括号。
>>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = [‘ banana‘, ‘ loganberry ‘, ‘passion fruit ‘] >>> [weapon.strip() for weapon in freshfruit] [‘banana‘, ‘loganberry‘, ‘passion fruit‘] >>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in ? [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two ‘for‘ >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9]
复杂的表达式和嵌套的方法也可以被包含在列表生成式中:
>>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] [‘3.1‘, ‘3.14‘, ‘3.142‘, ‘3.1416‘, ‘3.14159‘]
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]
这个列表生成式将会对行和列转置
>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
使用for来实现内嵌方法,它也可以是这样的:
>>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
任何的列表生成式都不用 ,它将会是这样的:
>>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
然而在现实世界中,我们并不希望写出如此复杂的语句,使用内置的zip()方法就可以轻松解决:
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
标签:
原文地址:http://www.cnblogs.com/andrew-chen/p/4949480.html