由于篇幅限制,写得太长查找起来不方便,我把这个总结分成了上下两篇,上片的链接为python 常用函数总结(上)。
Table of Contents
1 用[None]初始化
N = 4
ans = [None] * N
print(ans)
打印出的结果是[null,null,null,null]。可以用作for循环之前的初始化。
2 enumerate()函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环中。
enumerate(sequence, [start=0])
其中sequence为列表,元组或字符串; start为下标的起始位置,默认为0。
代码示例1:
seq = ['one', 'two', 'three']
print(list(enumerate(seq)))
输出结果为: [(0, 'one'), (1, 'two'), (2, 'three')]
代码示例2,在for循环中应用enumerate() 函数:
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
0 one
1 two
2 three
Leetcode中的这道题,922. Sort Array By Parity II,涉及到了这个函数,具体可参考我的github。
参考: http://www.runoob.com/python/python-func-enumerate.html
3 collections.deque()类型
不同于list只能添加新元素到右侧,Python的collections中的deque可以从左右两侧添加元素,同时它也支持从左侧去掉一项或者右侧去掉一项返回的是一个新的deque。
具体用法为:
import collections
q = collections.deque()
print(q)
q.append(2) # add to the right side
q.append(3)
print(q)
q.appendleft(1) # add to the left side
print(q)
q.pop() # Remove and return an element from the right side of the deque
print(q)
q.popleft() # Remove and return an element from the left side of the deque
print(q)
整个过程中打印的结果是:
deque([])
deque([2, 3])
deque([1, 2, 3])
deque([1, 2])
deque([2])
LeetCode中的这道题,933. Number of Recent Calls,涉及到了这个用法,具体可以参考我的github。