解压可迭代对象赋值给多个变量
1 | items = [1, 10, 7, 4, 5, (1,2,3)] |
保留最后 N 个元素
1 | from collections import deque |
不指定,那么无限大小队列
1 | >>> q = deque() |
在队列两端插入或删除元素时间复杂度都是 ``O(1)`` ,区别于列表,在列表的开头插入或删除元素的时间复杂度为 ``O(N)``
从一个集合中获得最大或者最小的 N 个元素列表
heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
1 |
|
对集合进行排序
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> import heapq
>>> heap = list(nums)
>>> heapq.heapify(heap) # 从小到大排序
>>> heap
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
>>>
>>> heapq.heappop(heap) # 弹出最小元素
-4
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
2
####
1
2
3
4>>> line = 'asdf fjdk; afed, fjek,asdf, foo'
>>> import re
>>> re.split(r'[;,\s]\s*', line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
按顺序插入字典
1 | from collections import OrderedDict |
在两个字典中寻找相同点(比如相同的键、相同的值等等)
1 | a = { |
不打乱顺序去重
1 | def dedupe(items): |
可用slice() 优化切片操作
1 | items = [0, 1, 2, 3, 4, 5, 6] |
看一下range函数
1
2
3
4
5
6
7
8
9
10
11
12 In [178]: a = (5,10,2)
In [179]: range(a)
In [180]: range(*a)
Out[180]: range(5, 10, 2)
* 就是将 a 中元素当 位置参数传进去
** 就是当字典
def kw_dict(**kwargs):
return kwargs
print kw_dict(a=1,b=2,c=3) == {'a':1, 'b':2, 'c':3}