python小技巧

python
1、拆箱:

a,b,c=1,2,3
a,b,c=[1,2,3]
a,(b,c),d=[1,[2,3],4]
#b为2,c为3
a,*b,c=[1,2,3,4,5]
#b为[2,3,4] 。仅支持py3

2、zip压缩与解压

 a = [1, 2, 3]
 b = ['a', 'b', 'c']
z = zip(a, b)
#(1, 'a'), (2, 'b'), (3, 'c')]
zip(*z)
#[(1, 2, 3), ('a', 'b', 'c')]

3、列表元素zip

a = [1, 2, 3, 4, 5, 6]
zip(*([iter(a)] * 2))
#[(1, 2), (3, 4), (5, 6)]
group_adjacent = lambda a, k: zip(*([iter(a)] * k))
group_adjacent(a, 3)
#[(1, 2, 3), (4, 5, 6)]

4、滑动取值

def n_grams(a, n):
     z = [iter(a[i:]) for i in range(n)]
     return zip(*z)

 a = [1, 2, 3, 4, 5, 6]
n_grams(a, 3)
#[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

5、双向队列

Q = collections.deque()
Q.append(1)
Q.appendleft(2)
Q.extend([3, 4])
Q.extendleft([5, 6])
Q
#deque([6, 5, 2, 1, 3, 4])
Q.pop()
#4
Q.popleft()
#6

6、快速频数统计

A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
A
#Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})
A.most_common(3)
#[(3, 4), (1, 2), (2, 2)]

7、生成器

g = (x ** 2 for x in xrange(10))  
next(g)
#0
next(g)
#1

你可能感兴趣的:(python小技巧)