List:
-
Add an item to the end of the list; equivalent to
a[len(a):] = [x]
.
list.
append
(x)
-
Extend the list by appending all the items in the given list; equivalent to
a[len(a):]=L
.
list.
extend
(L)
-
Insert an item at a given position. The first argument is the index of theelement before which to insert, so
a.insert(0,x)
inserts at the front ofthe list, anda.insert(len(a),x)
is equivalent toa.append(x)
.
list.
insert
(i,x)
-
Remove the first item from the list whose value is x. It is an error if thereis no such item.
list.
remove
(x)
-
Remove the item at the given position in the list, and return it. If no indexis specified,
a.pop()
removes and returns the last item in the list. (Thesquare brackets around thei in the method signature denote that the parameteris optional, not that you should type square brackets at that position. Youwill see this notation frequently in the Python Library Reference.)
list.
pop
([i])
-
Return the index in the list of the first item whose value is x. It is anerror if there is no such item.
list.
index
(x)
-
Return the number of times x appears in the list.
list.
count
(x)
-
Sort the items of the list in place (the arguments can be used for sortcustomization, se
e sorted()
for their explanation).
list.
sort
(cmp=None,key=None,reverse=False)
-
Reverse the elements of the list, in place
例子:
-
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()
>>> 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]
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
参考文献:https://docs.python.org/2/tutorial/datastructures.html#data-structures
https://docs.python.org/2/tutorial/introduction.html#lists