itertools 模块学习

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)]

 

 

 

 

 

 

 

 

posted @ 2024-12-02 17:09  zwx901323  阅读(7)  评论(0)    收藏  举报