標籤:
今天偶然看到一篇文章<你可能不知道的30個Python語言的提點技巧>,雖然做python有幾年了,但中間還是好多不知道或沒想到,特在這裡做下摘抄.
原文地址: http://soft.chinabyte.com/database/379/12920379.shtml
1. 命名切片
>>> a = [0, 1, 2, 3, 4, 5]>>> LASTTHREE = slice(-3, None)>>> LASTTHREEslice(-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)]
Python之幾個技巧特點