Reverse the elements of the list, in place.
You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.
你可能注意到了,像insert,remove和sort方法只是改变了list的数值而没有输出,因为他们的返回值送None,这是Python中所有可变数据结构的设计原则。
例如
a = [1, 2, 333, -1, 333, 13.89, 'Test']
a.append(4)
# [1, 2, 333, -1, 333, 13.89, 'Test', 4]
a.extend(range(1, 11))
# [1, 2, 333, -1, 333, 13.89, 'Test', 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.count(333)
# 2
a.insert(1, 'a')
# [1, 'a', 2, 333, -1, 333, 13.89, 'Test', 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.remove(1)
# ['a', 2, 333, -1, 333, 13.89, 'Test', 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.pop()
# ['a', 2, 333, -1, 333, 13.89, 'Test', 4, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.pop(3)
# ['a', 2, 333, 333, 13.89, 'Test', 4, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print a.index(2)
# 1
print a.count(333)
# 2
a.sort()
# [1, 2, 2, 3, 4, 4, 5, 6, 7, 8, 9, 13.89, 333, 333, 'Test', 'a']
a.reverse()
# ['a', 'Test', 333, 333, 13.89, 9, 8, 7, 6, 5, 4, 4, 3, 2, 2, 1]
Using Lists as Stacks(使用list作为栈)
利用list的方法可以简单的实现栈,由于栈是“后进先出”原则,可以利用append()和pop()方法来模拟栈
stack = [1, 2, 3]
stack.append(4)
stack.append(5)
# [1, 2, 3, 4, 5]
stack.pop()
# [1, 2, 3, 4]
Using Lists as Queues(使用list作为队列)
利用list的方法可以实现队列,由于队列是“先进先出原则”,可以利用append()和pop()方法,但是这不是最有效的,因为这样,每个元素的都有对应的移动一位。要实现一个队列,请使用collections.deque,它被设计为从两端快速添加和弹出。
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")
# deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
queue.popleft()
queue.popleft()
# deque(['Michael', 'Terry', 'Graham'])