1.建立無限迴圈迭代物件:count,cycle,repeat
from itertools import count for i in count(1, 2): if i > 10: break print(i) # 以1開始,2為步長,無限range結果:1 3 5 7 9
from itertools import cycle colors = cycle(['red', 'green', 'blue']) for i in range(6): print(next(colors), end=",") # 對給定的可迭代物件進行無限迴圈:red,green,blue,red,green,blue
from itertools import repeat for i in repeat('hello', 3): print(i) # 重複hello這個物件。如果指定了times引數,就重複times次;如果不指定,就無限重複:
2.累加求和計算:accumulate
from itertools import accumulate numbers = [1, 2, 3, 4, 5] print(list(accumulate(numbers))) # 計算可迭代物件的累積結果。預設情況下,它計算的是累加和 # 示例:1、1 + 2、1+2+3、1+2+3 + 4、1+2+3+4+5的結果
3.拆分序列:chan
from itertools import chain list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] for i in chain(list1, list2): print(i) # 先列印出list1中的元素 1、2、3,然後列印出list2中的元素a、b、c
4.篩選結果:dropwhile, takewhile
from itertools import dropwhile numbers = [1, 3, 5, 2, 4] result = dropwhile(lambda x: x % 2 == 1, numbers) print(list(result)) numbers = [1, 3, 5, 2, 4] result = filter(lambda x: x % 2 == 0, numbers) print(list(result))
from itertools import takewhile
numbers = [1, 3, 5, 2, 4] result = takewhile(lambda x: x % 2 == 1, numbers) print(list(result)) numbers = [1, 3, 5, 2, 4] result = filter(lambda x: x % 2 == 1, numbers) print(list(result))
5.全部自由組合:permutations,combinations,combinations_with_repalcement,pairwise
引數:選取幾個字母組合,2就是2個字母
from itertools import permutations letters = ['a', 'b', 'c'] print(list(permutations(letters, 2))) #結果:[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
from itertools import combinations letters = ['a', 'b', 'c'] print(list(combinations(letters, 2))) #結果:[('a', 'b'), ('a', 'c'), ('b', 'c')]
from itertools import combinations_with_replacement letters = ['a', 'b', 'c'] print(list(combinations_with_replacement(letters, 2))) #結果:[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
from itertools import pairwise numbers = [1, 2, 3, 4, 5] pairs = pairwise(numbers) print(list(pairs)) #結果:[(1, 2), (2, 3), (3, 4), (4, 5)]