itertools为python内置的标准库,用于处理可迭代对象的工具包。
count from itertools import count # def count(firstval=0, step=1): # 默认初始值为0, 步长为 1 # x = firstval # while 1: # 迭代器永远都会返回值。不会停止。 # yield x # x += step for i in zip(count(1), ['a', 'b', 'c']): print(i) for i in zip(count(3, 2), ['a', 'b', 'c']): # 初始值为3, 步长为 2 print(i)运行结果
(1, 'a') (2, 'b') (3, 'c') (3, 'a') (5, 'b') (7, 'c')count 生成的迭代器,用for循环取值可以无限循环下去,直到内存耗尽。如
b = count(1, 1) for i in b: print(i) (无限循环) 534585 534586 534587 534588 534589 534590 534591 534592 534593 534594 Process finished with exit code -1 cycle 和count一样,可以无限循环,和count不一样的是,count的参数只能是数字(小数或整数),cycle可以是任何数据类型 cycle(iterable) --> cycle object Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. 返回可迭代对象中的元素,直到全部取完,然后无限循环一步, a = cycle([{'a': 1, 'c': 2}, 'b', [3, 2]]) for i in a: print(i)运行结果
(无限循环) {'a': 1, 'c': 2} b [3, 2] {'a': 1, 'c': 2} b [3, 2] {'a': 1, 'c': 2} Process finished with exit code -1 repeat可设定重复次数 a = repeat(1, 5) for i in a: print(i)运行结果
1 1 1 1 1 Process finished with exit code 0