python之itertools


Python的內建模塊itertools提供了非常有用的用於操作迭代對象的函數。

count 創建一個迭代器,生成從n開始的連續整數,如果忽略n,則從0開始計算(注意:此迭代器不支持長整數)

如果超出了sys.maxint,計數器將溢出並繼續從-sys.maxint-1開始計算

import itertools
for item in itertools.count(1,3):
      if item>20:
       break
      print(item)
...
1
4
7
10
13
16
19
>>>

傳入一個序列,無限循環下去:
import itertools
its=["a","b","c","d"]
for item in itertools.cycle(its):
    print (item)
a
b
c
d
a
b
.
.
.

創建一個迭代器,重復生成object,times(如果已提供)指定重復計數,如果未提供times,將無止盡返回該對象。
import itertools
its=["a","b","c"]
for item in itertools.repeat(its,4):
    print (item)
    

itertools.chain(*iterables)
*iterables為一個或多個可迭代序列
作用:返回所有可迭代序列

import itertools
its=["a","b","c","d"]
hers=["A","B","C","D"]
others=["1","2","3","4"]
for item in itertools.chain(its,hers,others):
    print (item)
...
a
b
c
d
A
B
C
D
1
2
3
4


[2] compress
itertools.compress(data, selectors)
data為數據對象
selectors為選擇器(規則)
作用:返回數據對象中對應規則為True的元素
import itertools

its=["a","b","c","d","e","f","g","h"]
selector=[True,False,1,0,3,False,-2,"y"]
for item in itertools.compress(its,selector):
    print (item)
...
a
c
e
g
h

[x for x in filter(None,range(2,10))]
list(filter(None,range(2,10)))
chain.from_iterable()
將單個iterable中的所有元素拼接輸出。
d=['串一株幸運草','串一個同心圓']
for i in itertools.chain.from_iterable(d):
    print(i)
...














dropwhile()
itertools.dropwhile(predicate, iterable)
從頭開始,干掉不符合的元素,直到第一個正確元素。    
for i in itertools.dropwhile(lambda x:x<7,[1,2,3,6,7,8,2,4,5,9]):
   print(i)
...
7
8
2
4
5
9

filterfalse()
輸出為錯的要素:
for i in itertools.filterfalse(lambda x:x=='moyu',['moyu','jinye']):
    print(i)
...
jinye

groupby()
itertools.groupby(iterable, key=None)
將iterable同要素聚合輸出:
for k,g in itertools.groupby('aaAAaBBBCCCCC'):
    print(k)
    print(list(g))
...
a
['a', 'a']
A
['A', 'A']
a
['a']
B
['B', 'B', 'B']
C
['C', 'C', 'C', 'C', 'C']

islice()
切片操作的迭代器版本
>>> for i in itertools.islice('fengliutitangShawn',0,None,2):
...     print(i)
...
f
n
l
u
i
a
g
h
w

tee()
itertools.tee(iterable, n=2)
創建n個與iterable相同的獨立迭代器。
for i in itertools.tee([1,2,3,4,5,6]):
    for j in i:
        print(j)
...
1
2
3
4
5
6
1
2
3
4
5
6

組合生成器
product()
itertools.product(*iterables[,repeat=1])
對*iterables進行笛卡爾積運算
for i in itertools.product('Tom','Jerry',repeat=1):
    print(i)
...
('T', 'J')
('T', 'e')
('T', 'r')
('T', 'r')
('T', 'y')
('o', 'J')
('o', 'e')
('o', 'r')
('o', 'r')
('o', 'y')
('m', 'J')
('m', 'e')
('m', 'r')
('m', 'r')
('m', 'y')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM