必看的的30个python语言的特点技巧(3)

1.30 最大最小元素 (heapq.nlargest和heapq.nsmallest)

>>> a = [random.randint(0, 100) for in xrange(100)]

>>> heapq.nsmallest(5, a)

[3, 3, 5, 6, 8]

>>> heapq.nlargest(5, a)

[100, 100, 99, 98, 98]

1.31 笛卡尔乘积 (itertools.product)

>>> for p in itertools.product([1, 2, 3], [4, 5]):

(1, 4)

(1, 5)

(2, 4)

(2, 5)

(3, 4)

(3, 5)

>>> for p in itertools.product([0, 1], repeat=4):

… print ”.join(str(x) for x in p)

0000

0001

0010

0011

0100

0101

0110

0111

1000

1001

1010

1011

1100

1101

1110

1111

1.32 组合的组合和置换 (itertools.combinations 和 itertools.combinations_with_replacement)

>>> for c in itertools.combinations([1, 2, 3, 4, 5], 3):

… print ”.join(str(x) for x in c)

123

124

125

134

135

145

234

235

245

345

>>> for c in itertools.combinations_with_replacement([1, 2, 3], 2):

… print ”.join(str(x) for x in c)

11

12

13

22

23

33

1.33 排序 (itertools.permutations)

>>> for p in itertools.permutations([1, 2, 3, 4]):

… print ”.join(str(x) for x in p)

1234

1243

1324

1342

1423

1432

2134

2143

2314

2341

2413

2431

3124

3142

3214

3241

3412

3421

4123

4132

4213

4231

4312

4321

1.34 链接的迭代 (itertools.chain)

>>> a = [1, 2, 3, 4]

>>> for p in itertools.chain(itertools.combinations(a, 2), itertools.combinations(a, 3)):

… print p

(1, 2)

(1, 3)

(1, 4)

(2, 3)

(2, 4)

(3, 4)

(1, 2, 3)

(1, 2, 4)

(1, 3, 4)

(2, 3, 4)

>>> for subset in itertools.chain.from_iterable(itertools.combinations(a, n) for n in range(len(a) + 1))

… print subset

()

(1,)

(2,)

(3,)

(4,)

(1, 2)

(1, 3)

(1, 4)

(2, 3)

(2, 4)

(3, 4)

(1, 2, 3)

(1, 2, 4)

(1, 3, 4)

(2, 3, 4)

(1, 2, 3, 4)

1.35 按给定值分组行 (itertools.groupby)

>>> from operator import itemgetter

>>> import itertools

>>> with open(‘contactlenses.csv’, ‘r’) as infile:

… data = [line.strip().split(‘,’) for line in infile]

>>> data = data[1:]

>>> def print_data(rows):

… print ‘\n’.join(‘\t’.join(‘{:

Posted in 未分类