Python之几个技巧特点

时间:2020-12-16 16:09:57

今天偶然看到一篇文章<你可能不知道的30个Python语言的提点技巧>,虽然做python有几年了,但中间还是好多不知道或没想到,特在这里做下摘抄.

原文地址: http://soft.chinabyte.com/database/379/12920379.shtml

1. 命名切片

>>> a = [, , , , , ]

>>> LASTTHREE = slice(-, None)

>>> LASTTHREE

slice(-, None, None)

>>> a[LASTTHREE]

[, , ]

2. zip 打包和解包列表

>>> a = [, , ]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(, 'a'), (, 'b'), (, 'c')]
>>>
>>> zip(*z)
[(, , ), ('a', 'b', 'c')]

3. 使用 zip 合并相邻的列表项

>>> a=[,,,,]
>>> zip(*([iter(a)]*))
[(, ), (, ), (, )]
>>>
>>> zip(a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]

可以写成个匿名函数

group_adjacent_1 = lambda a, k:zip(*([iter(a)]*k))

group_adjacent_2 = lambda a, k:zip(*(a[i::k] for i in range(k)))

其中 a 标识要合并的列表, k 表示要合并相邻的 k 个元素

>>> group_adjacent_1(a, )
[(, , ), (, , )]
>>> group_adjacent_1(a, )
[(,), (,), (,), (,), (,), (,)]
>>>
>>>
>>> group_adjacent_2(a, 3)
[(1, 2, 3), (4, 5, 6)]
>>> group_adjacent_2(a, 1)
[(1, 2, 3), (4, 5, 6)]

4. 使用zip和iterators生成滑动窗口

>>> from itertools import islice
>>> def n_grams(a, n):
... z=(islice(a, i, None) 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)]