每次寫python都是各種查資料,之前搜過的東西腦子裡大緻有個印象,但是又寫不出來qaq,是以記錄一下每天學會的函數什麼的…(具體描述和例子非原創)
itertools
combinations()
combinations(iterable,r);
建立一個疊代器,傳回iterable中所有長度為r的子序列,傳回的子序列中的項按輸入iterable中的順序排序
for i in combinations([1, 2, 3], 2):
print i
--------------------------------
(1, 2)
(1, 3)
(2, 3)
combinations_with_replacement()
for i in combinations_with_replacement([1, 2, 3], 2):
print i
-----------------------------------------------------
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
chain()
使用形式:
chain(iterable1, iterable2, iterable3, ...)
chain 接收多個可疊代對象作為參數,将它們『連接配接』起來,作為一個新的疊代器傳回。
>>> from itertools import chain
>>>
>>> for item in chain([1, 2, 3], ['a', 'b', 'c']):
... print item
...
1
2
3
a
b
c
還可以這樣
letters = ['a', 'b', 'c', 'd', 'e', 'f']
booleans = [1, 0, 1, 0, 0, 1]
print(list(itertools.chain(letters,booleans)))
# ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1]
print(tuple(itertools.chain(letters,letters[3:])))
# ('a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f')
print(set(itertools.chain(letters,letters[3:])))
# {'a', 'd', 'b', 'e', 'c', 'f'}
print(list(itertools.chain(letters,letters[3:])))
# ['a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f']
chain.from_iterable()
接收一個可疊代對象作為參數,傳回一個疊代器
>>> string = chain.from_iterable('ABCD')
>>> string.next()
'A'
之前使用過
list(chain.from_iterable(list of a list))
把 list of a list 鋪平,變成一個 list
參考:
- python itertools功能詳解
- 高效的 itertools 子產品