Python3之itertools模塊


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

1、Infinite Iterators

Iterator Arguments Results Example

count()

start, [step]

start, start+step, start+2*step, ...

count(10) --> 10 11 12 13 14 ...

cycle()

p

p0, p1, ... plast, p0, p1, ...

cycle('ABCD') --> ...

repeat()

elem [,n]

elem, elem, elem, ... endlessly or up to n times

repeat(10, 3) --> 10 10 10  

 

1.1 count

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

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

>>> import itertools
>>> n = itertools.count(1)
>>> for i in n:
	print(i)
	
1
2
3
4
......

1.2 cycle

  傳入一個序列,無限循環下去:  

>>> itertools.cycle('ABCDE')
<itertools.cycle object at 0x00000000033576C8>
>>> for i in itertools.cycle('ABCDE'):
	print(i)

	
A
B
C
D
E
A
B
.....

1.3 repeat

  創建一個迭代器,重復生成object,times(如果已提供)指定重復計數,如果未提供times,將無止盡返回該對象。

>>> s = itertools.repeat('ABC',4)
>>> s
repeat('ABC', 4)
>>> for i in s:
	print(i)

	
ABC
ABC
ABC
ABC
>>> 

  

2、Iterators terminating on the shortest input sequence

Iterator

Arguments

Results

Example

accumulate()

p [,func]

p0, p0+p1, p0+p1+p2, ...

accumulate([1,2,3,4,5]) --> 1 3 6 10 15

chain()

p, q, ...

p0, p1, ... plast, q0, q1, ...

chain('ABC', 'DEF') --> A B C D E F

chain.from_iterable()

iterable

p0, p1, ... plast, q0, q1, ...

chain.from_iterable(['ABC', 'DEF']) --> A B C DE F

compress()

data, selectors

(d[0] if s[0]), (d[1] if s[1]), ...

compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F

dropwhile()

pred, seq

seq[n], seq[n+1], starting when pred fails

dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1

filterfalse()

pred, seq

elements of seq where pred(elem) is false

filterfalse(lambda x: x%2, range(10)) --> 0 2 46 8

groupby()

iterable[, keyfunc]

sub-iterators grouped by value of keyfunc(v)

 

islice()

seq, [start,] stop [, step]

elements from seq[start:stop:step]

islice('ABCDEFG', 2, None) --> C D E F G

starmap()

func, seq

func(*seq[0]), func(*seq[1]), ...

starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 91000

takewhile()

pred, seq

seq[0], seq[1], until pred fails

takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4

tee()

it, n

it1, it2, ... itn splits one iterator into n

 

zip_longest()

p, q, ...

(p[0], q[0]), (p[1], q[1]), ...

zip_longest('ABCD', 'xy', fillvalue='-') --> AxBy C- D-

 

2.1 chain

  將多個迭代器作為參數, 但只返回單個迭代器, 它產生所有參數迭代器的內容, 就好像他們是來自於一個單一的序列.  

>>> for c in itertools.chain('ABC', 'XYZ'):
...     print(c)
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'

2.2 groupby

  返回一個產生按照key進行分組后的值集合的迭代器.

  如果iterable在多次連續迭代中生成了同一項,則會定義一個組,如果將此函數應用一個分類列表,那么分組將定義該列表中的所有唯一項,key(如果已提供)是一個函數,應用於每一項,如果此函數存在返回值,該值將用於后續項而不是該項本身進行比較,此函數返回的迭代器生成元素(key, group),其中key是分組的鍵值,group是迭代器,生成組成該組的所有項。 

>>> for key, group in itertools.groupby('AAABBBCCAAA'):
...     print(key, list(group))
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']

  實際上挑選規則是通過函數完成的,只要作用於函數的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函數返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素'A''a'都返回相同的key:

>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
...     print(key, list(group))
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']

  

3、Combinatoric generators 

Iterator

Arguments

Results

product()

p, q, ... [repeat=1]

cartesian product, equivalent to a nested for-loop

permutations()

p[, r]

r-length tuples, all possible orderings, no repeated elements

combinations()

p, r

r-length tuples, in sorted order, no repeated elements

combinations_with_replacement()

p, r

r-length tuples, in sorted order, with repeated elements

product('ABCD', repeat=2)

 

AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD

permutations('ABCD', 2)

 

AB AC AD BA BC BD CA CB CD DA DB DC

combinations('ABCD', 2)

 

AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)

 

AA AB AC AD BB BC BD CC CD DD

 

3.1 product(*iterables[, repeat]) 笛卡爾積

  創建一個迭代器,生成表示item1,item2等中的項目的笛卡爾積的元組,repeat是一個關鍵字參數,指定重復生成序列的次數。 

>>> a = (1,2,3)
>>> b = ('A','B','C')
>>> c = itertools.product(a,b)
>>> for i in c:
	print(i)
	
(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')  

3.2 permutations(iterable[, r]) 排列

  創建一個迭代器,返回iterable中所有長度為r的項目序列,如果省略了r,那么序列的長度與iterable中的項目數量相同: 返回p中任意取r個元素做排列的元組的迭代器 

>>> a = [1, 2, 3, 4]
>>> s = [i for i in itertools.permutations(a,3)] # 從序列a中選出3個元素進行排列
>>> s
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]
>>> s_number = [i[0]*100 + i[1]*10 + i[2] for i in s]  # 選出的3個數字組合成不重復的3位數
>>> s_number
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
>>> 

3.3 combinations(iterable, r) 組合

  創建一個迭代器,返回iterable中所有長度為r的子序列,返回的子序列中的項按輸入iterable中的順序排序 (不帶重復)   

>>> a = [1, 2, 3, 4]
>>> s = [i for i in itertools.combinations(a,2)] # 從序列a中選出2個不重復的元素
>>> s
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

 

更多詳細信息請查看官網介紹:https://docs.python.org/3.5/library/itertools.html


免責聲明!

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



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