>>>from random import*>>> seed(10)>>>print(random())0.5714025946899135>>>print(random())0.4288890546751146>>> seed(10)>>>print(random())0.5714025946899135
>>>from collections import deque
>>> d = deque("abcde")>>> d.append('f')>>> d
deque(['a','b','c','d','e','f'])>>> d.appendleft('z')>>> d
deque(['z','a','b','c','d','e','f'])>>> d.pop()'f'>>> d.popleft()'z'>>> d
deque(['a','b','c','d','e'])
import itertools
排列组合迭代器
>>>import itertools
>>>###### itertools.product() 笛卡尔积 ##########>>>for i in itertools.product('ABC','01'):...print(i)...('A','0')('A','1')('B','0')('B','1')('C','0')('C','1')>>>for i in itertools.product('AB', repeat=2):...print(i)...('A','A')('A','B')('B','A')('B','B')>>>for i in itertools.product('AB', repeat=3):...print(i)...('A','A','A')('A','A','B')('A','B','A')('A','B','B')('B','A','A')('B','A','B')('B','B','A')('B','B','B')>>>###### itertools.permutations() 排列 ##########>>>for i in itertools.permutations('ABCD',3):# 排列长度为3...print(i)...('A','B','C')('A','B','D')('A','C','B')('A','C','D')('A','D','B')('A','D','C')('B','A','C')('B','A','D')('B','C','A')('B','C','D')('B','D','A')('B','D','C')('C','A','B')('C','A','D')('C','B','A')('C','B','D')('C','D','A')('C','D','B')('D','A','B')('D','A','C')('D','B','A')('D','B','C')('D','C','A')('D','C','B')>>>for i in itertools.permutations(range(3)):...print(i)...(0,1,2)(0,2,1)(1,0,2)(1,2,0)(2,0,1)(2,1,0)>>>###### itertools.combinations() 组合 ##########>>>for i in itertools.combinations('ABCD',2):...print(i)...('A','B')('A','C')('A','D')('B','C')('B','D')('C','D')>>>for i in itertools.combinations(range(4),2):...print(i)...(0,1)(0,2)(0,3)(1,2)(1,3)(2,3)>>>for i in itertools.combinations_with_replacement('ABCD',2):# 可重复...print(i)...('A','A')('A','B')('A','C')('A','D')('B','B')('B','C')('B','D')('C','C')('C','D')('D','D')
拉链
>>>for i inzip('abc','012','ABCD'):# 执行到最短的一条结束,zip是内置函数,不需增加itertools...print(i)...('a','0','A')('b','1','B')('c','2','C')>>>for i in itertools.zip_longest('abc','012','ABCD'):...print(i)...('a','0','A')('b','1','B')('c','2','C')(None,None,'D')>>>for i in itertools.zip_longest('abc','012','ABCD', fillvalue='?'):...print(i)...('a','0','A')('b','1','B')('c','2','C')('?','?','D')
其他
>>>for i in itertools.repeat(10,3):# 重复...print(i)...101010
>>>for i in itertools.chain('abc',[1,2,3]):# chain()将多串迭代器串联起来...print(i)...
a
b
c
123
>>>for i inenumerate('python', start=1):# 内置函数,枚举...print(i)...(1,'p')(2,'y')(3,'t')(4,'h')(5,'o')(6,'n')