5.1 关于列表的知识:

  • list.append(x)把一个元素添加到列表队尾,相当于a[len(a):]=[x].
  • list.extend(L):讲一个列表的元素都添加到另一个列表上
  • list.insert(i,x):在制定一个位置插入一个元素
  • list.remove(x):删除列表中值为x 的第一个元素,如果没有,就返回一个错误
  • list.pop(i)从列表的指定位置删除元素,并将其返回
  • list.clear()删除所有元素
  • list.index()相当于返回列表中第一个值为x的索引,如果没有,就会返回一个错误
  • list.count(x)返回x在列表中出现的次数
  • list.sort()对列表排序
  • list.reverse()反排序
  • list.copy()等于a[:]

5.11把列表当做堆栈使用

  • append,pop方法

5.1.2 队列使用

  • collection.deque他是为首尾两端快速插入和删除而设计的
>>> from collections import deque
>>> queue =deque(["Eric","John","Michael"])
>>> queue
deque(['Eric', 'John', 'Michael'])
>>> queue.append("Terry")
>>> queue
deque(['Eric', 'John', 'Michael', 'Terry'])
>>> queue.popleft()
'Eric'
>>> queue
deque(['John', 'Michael', 'Terry'])
>>> queue.popright()
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    queue.popright()
AttributeError: 'collections.deque' object has no attribute 'popright'
>>> 
复制代码

5.1.3 列表推导式

>>> squares=[]
>>> for x in range(10):
	squares.append(x**)
	

>>> for x in range(10):
        squares.append(x**2)

        
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
复制代码

或者函数式编程:

squares=list(map(lambda x:x**2,range(10)))

##或者

squares=[x**2 for x in 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)
复制代码
>>> 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]
复制代码