1. 程式人生 > 其它 >Python常用內建模組——itertools

Python常用內建模組——itertools

技術標籤:藍橋杯Python

itertools是Python自帶的一個非常實用的模組,甚至是百度翻譯都對其用途“熟稔於心”。

itertools 模組包含了一系列用來產生不同型別迭代器的函式或類,這些函式的返回都是一個迭代器,我們可以通過 for 迴圈來遍歷取值,也可以使用 next() 來取值。

這裡也順便提一下next()函式:
作為Python內建函式,
next() 返回迭代器的下一個專案;
next() 函式要和生成迭代器的 iter() 函式一起使用。

mylist = iter(["apple", "banana", "cherry"
]) x = next(mylist) print(x) x = next(mylist) print(x) x = next(mylist) print(x)

執行結果:

apple
banana
cherry
mylist = iter(["apple", "banana", "cherry"])
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange"
) print(x) x = next(mylist, "orange") print(x)

執行結果:

apple
banana
cherry
orange

itertools 模組提供的迭代器函式有以下幾種型別:

無限迭代器:生成一個無限序列,比如自然數序列 1, 2, 3, 4, …;

有限迭代器:接收一個或多個序列(sequence)作為引數,進行組合、分組和過濾等;

組合生成器:序列的排列、組合,求序列的笛卡兒積等;

itertools中的函式:

部分功能示例:

無限迭代器

count
count() 接收兩個引數,第一個引數為起始值,預設為 0,第二個引數為步長,預設為 1。

#encoding:utf-8
import itertools

nums = itertools.count(2,2)
for i in nums:
  if i == 10:
    break
  else:
    print(i)

執行結果:

2
4
6
8

repeat
repeat() 用於反覆生成一個 object:

for item in itertools.repeat('hello world', 3):
    print(item)

for item in itertools.repeat([1, 2, 3, 4], 3):
    print(item)

執行結果:

hello world
hello world
hello world
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]

cycle

cycle_strings = itertools.cycle('ABC')
i = 1
for string in cycle_strings:
    if i == 10:
       break
    else:
       print(i, string)
       i += 1

執行結果:

1 A
2 B
3 C
4 A
5 B
6 C
7 A
8 B
9 C

有限迭代器

compress
compress 可用於對資料進行篩選,當 selectors 的某個元素為 true 時,則保留 data 對應位置的元素,否則去除:

print(list(itertools.compress('ABCDEF', [1, 1, 0, 1, 0, 1])))

print(list(itertools.compress('ABCDEF', [1, 1, 0, 1])))

print(list(itertools.compress('ABCDEF', [True, False, True])))

執行結果:

['A', 'B', 'D', 'F']
['A', 'B', 'D']
['A', 'C']

dropwhile
dropwhile包含兩個引數,
形式如dropwhile(predicate, iterable)
其中,predicate 是函式,iterable 是可迭代物件。對於 iterable 中的元素,如果 predicate(item) 為 true,則丟棄該元素,否則返回該項及所有後續項。

print(list(itertools.dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1])))

執行結果:

[6, 2, 1]

islice
islice 是切片選擇,它的使用形式為:islice(iterable, [start,] stop [, step])

print(list(itertools.islice([10, 6, 2, 8, 1, 3, 9], 5)))

print(list(itertools.islice([10, 6, 2, 8, 1, 3, 9], 2,5,1)))

執行結果:

[10, 6, 2, 8, 1]
[2, 8, 1]

組合生成器

permutations
生成全排列

print(list(itertools.permutations('ABC')))

print(list(itertools.permutations('ABC', 2)))

執行結果:

[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

combinations
產生組合

print(list(itertools.combinations('ABC', 2)))

print(list(itertools.combinations_with_replacement('ABC', 2)))

執行結果:

[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

相關博文參考:

babay神——python 高效的 itertools 模組