import itertools
s=itertools.count(2,2)#输入从2开始步长为2
for i in s:
if i >100:
break
print(i)
import itertools
s=itertools.cycle('456')#重复输入456
for i in s:
print(i)
import itertools
s=itertools.repeat('456',5)#重复输入5遍456
for i in s:
print(i)
import itertools
s=itertools.count(1)
n=itertools.takewhile(lambda x:x<=20,s)#把lambda作用于s直到结果不再为True
print(list(n))
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
chain()可以把一组迭代对象串联起来,形成一个更大的迭代器:
import itertools
for j in itertools.chain('456','789'):
print(j)
#456789
groupby()把迭代器中相邻的重复元素挑出来放在一起:
import itertools
for i ,group in itertools.groupby('AABBGGT'):
#for i, group in itertools.groupby('AABBGGTt',lambda x:x.supper()):忽略大小写
print(i,list(group))```
import itertools
def pi(N):
’ 计算pi的值 ’
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, …
result_iter=itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, …, 2N-1.
result = itertools.takewhile(lambda x:x<=2N-1, result_iter)#把lambda作用于result_iter结果为True
# print(list(result))
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, …
sum=0
n=1
for i in result:
if n%2!=0:
sum=sum+4/i
n+=1
else:
sum=sum+(-4/i)
n+=1
return sum
# step 4: 求和:
print(pi(2))