标签:
今天偶然看到一篇文章<你可能不知道的30个Python语言的提点技巧>,虽然做python有几年了,但中间还是好多不知道或没想到,特在这里做下摘抄.
原文地址: http://soft.chinabyte.com/database/379/12920379.shtml
1. 命名切片
>>> a = [0, 1, 2, 3, 4, 5] >>> LASTTHREE = slice(-3, None) >>> LASTTHREE slice(-3, None, None) >>> a[LASTTHREE] [3, 4, 5]
2. zip 打包和解包列表
>>> a = [1, 2, 3] >>> b = [‘a‘, ‘b‘, ‘c‘] >>> z = zip(a, b) >>> z [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘)] >>> >>> zip(*z) [(1, 2, 3), (‘a‘, ‘b‘, ‘c‘)]
3. 使用 zip 合并相邻的列表项
>>> a=[1,2,3,4,5] >>> zip(*([iter(a)]*2)) [(1, 2), (3, 4), (5, 6)]
>>>
>>> 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, 3) [(1, 2, 3), (4, 5, 6)] >>> group_adjacent_1(a, 1) [(1,), (2,), (3,), (4,), (5,), (6,)]
>>>
>>>
>>> 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)]
标签:
原文地址:http://www.cnblogs.com/liuq/p/4353986.html