本节主要讲述python中常用的函数及函数模块:
- 一、 函数
- 1.1 常用函数
- 1.2 匿名(lambda)函数
- 1.3 生成器
- 1.3.1 迭代生成器(iterator)
- 1.3.2 生成器(generator)
- 1.4 itertools模块
- 1.4.1 常用无限迭代器(infinite iterators)
- 1.4.2 常用组合迭代器(Combinatoric Iterators)
- 1.4.3 常用有限迭代器(Iterators Terminating on the Shortest Input Sequence)
函数常用的自定义形式为:
>> def my_function(x,y,z=1.5): # x,y 为位置参数(positional),z为关键字参数(keyword),关键字参数必须位于位置参数(如果有的话)之后 >> if z>1: >> return z*(x+y) >> else: >> return z/(x+y)1.2 匿名(lambda)函数
使用lambda 声明一个匿名函数,如:lambda x:x**2
1.3 生成器 1.3.1 迭代生成器(iterator)一般地,在编程时,会经常使用到使用for循环遍历列表、字典、元组、集合以及字符串的情况,如下所示:
>> some_dict = {'a': 1, 'b': 2, 'c': 3}
>> for key in some_dict:
>> print(key)
[out]:a
b
c
>> dict_iterator=iter(some_dict)
>> dict_iterator
[out]:
>> list(dict_iterator)
[out]: ['a', 'b', 'c']
>> strings='miaomiao'
>> for string in strings:
>> print(string)
[out]:m
i
a
o
m
i
a
o
>> string_iterator=iter(strings)
>> string_iterator
[out]:
>> list(string_iterator)
[out]:['m', 'i', 'a', 'o', 'm', 'i', 'a', 'o']
如何理解上述过程?在编写for key in some_dict时,Python解释器首先会尝试从some_dict创建一个迭代器iter(some_dict),然后可遍历some_dict的key序列。
1.3.2 生成器(generator)自定义函数的return 一般会返回一个值,或者是几个值,但是通过生成器可返回具有某个特性的一系列值。 要创建一个生成器,只需将函数中的return替换为yeild即可:
>> def squares(n=10):
>> print('Generating squares from 1 to {0}'.format(n ** 2))
>> for i in range(1, n + 1):
>> yield i ** 2
>> gen = squares() # 调用该生成器时,没有任何代码会被立即执行:
>> gen
[out]:
>> for x in gen: # 直到从该生成器中请求元素时,它才会开始执行其代码:
>> print(x)
[out]:1 4 9 16 25 36 49 64 81 100
yield 生成器也可用生成器表达式替代。生成器表达式(generator expression)类似于列表推导式,把列表推导式两端的方括号改成圆括号
>> gen = (x ** 2 for x in range(100)) >> gen [out]:1.4 itertools模块at 0x7fbbd5ab29e8>
itertools提供了用于迭代计算的一系列封装的生成器函数,可以直接使用。使用方式为:import itertools
其中函数主要可以分为三类,分别是无限迭代器,有限迭代器,组合迭代器。
- itertools.count([start=0, step=1]) 生成自然数序列
count([start=0, step=1]) 接收两个可选整形参数,第一个指定了迭代开始的值,第二个指定了迭代的步长。此外,start参数默认为0,step参数默认为1,可以根据需要来把这两个指定为其它值,或者使用默认参数。
>> import itertools
>> for i in itertools.count(10,2):
>> print(i)
>> if i>15:
>> break
[out]: 10
12
14
16
- cycle(iterable) 是用一个可迭代对象中的元素来创建一个迭代器,并且复制自己的值,一直无限的重复下去。
>> import itertools
>> for i in itertools.cycle("abc"):
>> print(i) # 具有无限的输出,需要手动停止。
[out]:a
b
c
a
b
c
- repeat(elem [,n])是将一个元素重复n遍或者无穷多遍,并返回一个迭代器。
for i in itertools.repeat("abcd",5):
print(i)
1.4.2 常用组合迭代器(Combinatoric Iterators)
组合迭代器常用于生成排列、组合、笛卡尔积等数据。
- permutations(iterable,r=None)返回的是迭代元素的排列结果,r表示返回元组的长度。
>> for i in itertools.permutations('abc'):
>> print(i)
[out]:('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
- combinations(iterable,r) 返回的是迭代元素的组合结果,r表示返回元组的长度。
>> for i in itertools.combinations('abc',r=2):
>> print(i)
[out]: ('a', 'b')
('a', 'c')
('b', 'c')
- product(*iterables, repeat=1) 返回的是迭代元素的笛卡尔积, repeat 表示这些可迭代序列重复的次数。
>> import itertools
>> A = [1, 2, 3]
>> B = [100, 200, 300]
>> for item in itertools.product(A, B):
>> print(item)
[out]:(1, 100)
(1, 200)
(1, 300)
(2, 100)
(2, 200)
(2, 300)
(3, 100)
(3, 200)
(3, 300)
1.4.3 常用有限迭代器(Iterators Terminating on the Shortest Input Sequence)
- chain(*iterables) 可以把多个可迭代对象组合起来,形成一个更大的迭代器。
>> for i in itertools.chain('good','bye'):
>> print(i)
[out]:g
o
o
d
b
y
e
- groupby(iterable,key=None) 可以把相邻元素按照 key 函数分组,并返回相应的 key 和 groupby,如果key函数为 None,则只有相同的元素才能放在一组。
>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
>> print(key,list(group))
[out]: A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
- accumulate(iterable [,func]) 可以计算出一个迭代器,这个迭代器是由特定的二元函数的累计结果生成的,如果不指定的话,默认函数为累加函数。
>> for i in itertools.accumulate([0,1,2,3,4,5]):
>> print(i)
[out]:0
1
3
6
10
15
如果我们指定这个累计函数,则还能有不同的用法,例如,指定一个最大值函数,则为计算累计最大值:
>> for i in itertools.accumulate([2,1,4,3,5],max):
>> print(i)
[out]:2
2 # 2>1
4 # 2<4
4 # 4>3
5 # 4<5



