摘要:itertools模块介绍;常用的操作迭代对象函数:count(),cycle(),repeat(),takewhile(),chain(),groupby();计算圆周率
*写在前面:为了更好的学习python,博主记录下自己的学习路程。本学习笔记基于廖雪峰的Python教程,如有侵权,请告知删除。欢迎与博主一起学习Pythonヽ( ̄▽ ̄)ノ *
目录
常用内置模块
itertools
count( )
cycle( )
repeat( )
takewhile()
chain( )
groupby( )
【练习】计算圆周率pi
常见内置模块
itertools
itertools模块提供了常用的操作迭代对象的函数。
count( )
count( )函数可创建一个无限迭代器,输入参数是start,从哪开始;step,每隔几个输出一个,默认为0。
>>> import itertools
>>> natuals = itertools.count(1)
>>> for n in natuals:
... print(n)
...
1
2
3
...
cycle( )
cycle( )函数也是创建一个无限迭代器,把传入的序列无限循环输出。
>>> import itertools
>>> cs = itertools.cycle('AB') # 注意字符串也是序列的一种
>>> for c in cs:
... print(c)
...
'A'
'B'
'A'
'B'
'A'
'B'
...
repeat( )
repeat( )函数同样创建一个无限迭代器,把一个元素重复指定次数
>>> ns = itertools.repeat('A', 5)
>>> for n in ns:
... print(n)
...
A
A
A
A
A
takewhile()
如果一个无限序列在无限地迭代输出,我们只能用ctrl+c强制退出运行。
所以通过会借助takewhile( )函数添加条件,拿取有限序列。
>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 15, natuals)
>>> list(ns)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
需要注意的是,takewhile的第一个参数函数返回值一旦为False,则停止拿取。
chain( )
chain( )函数把一组迭代对象组合成更大的迭代器。
>>>import itertools
>>>for c in itertools.chain('AB','12'):
... print(c)
...
A
B
1
2
groupby( )
groupby( )函数将迭代器中的元素进行分组,如果相同的相邻元素会分成一组。
>>>import itertools
>>>for key, group in itertools.groupby('AA2222BBAA'):
... print(key, list(group))
...
A ['A', 'A']
2 ['2', '2', '2', '2']
B ['B', 'B']
A ['A', 'A']
我们还可以在添加一个函数作为参数,groupby就会根据函数的返回值是否相等来进行分组。比如忽略字母大小写进行分组:
>>>import itertools
>>>for key, group in itertools.groupby('AaAa222BbAA', lambda c: c.upper()):
... print(key, list(group))
...
A ['A', 'a', 'A', 'a']
2 ['2', '2', '2']
B ['B', 'b']
A ['A', 'A']
【练习】计算圆周率pi
(练习源自廖雪峰官网)
计算圆周率可以根据公式:π=(4/1)-(4/3)+(4/5)-(4/7)+...+(-1)n-1(2n-1)
利用Python提供的itertools模块,我们来计算这个序列的前N项和:
# -*- coding: utf-8 -*-
import itertools
def pi(N):
' 计算pi的值 '
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
ns = itertools.count(1, 2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
ns = itertools.takewhile(lambda x: x <= 2*N-1, ns)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
sum = 0
for i in ns:
sum = sum + (-1)**((i+1)/2-1)*4/i # (-1)**((i+1)/2-1)表示-1的n-1次方
# step 4: 求和:
return sum
# 测试:
print(pi(10))
print(pi(100))
print(pi(1000))
print(pi(10000))
assert 3.04 < pi(10) < 3.05
assert 3.13 < pi(100) < 3.14
assert 3.140 < pi(1000) < 3.141
assert 3.1414 < pi(10000) < 3.1415
print('ok')
运行结果:
ok
以上就是本节的全部内容,感谢你的阅读。
下一节内容:常用内置模块之 contextlib
有任何问题与想法,欢迎评论与吐槽。
和博主一起学习Python吧( ̄▽ ̄)~*
网友评论