🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[success] # 迭代对象专属 ~~~ 1.对迭代对象切片处理 --- itertools.islice(c,0,5) ---第一个参数迭代对象,第二个是起始位置,三结束位置 ~~~ >[danger] ##### 对迭代对象切片 itertools.islice ~~~ 1传统切片会报错,单这种切片只能用一次,因为迭代对象只能一次,可以用数组保存记录 ~~~ ~~~ import itertools def Count(): n = 10 while n>1: yield n n -=1 c = Count() # print(c[0:5]) a = itertools.islice(c,0,5) print(a) for i in a: print(i) 打印结果: <itertools.islice object at 0x000001A766CB9598> 10 9 8 7 6 ~~~ >[danger] ##### 循环时候跳过某些选项--dropwhile: ~~~ 1.第一个元素是判断,如果是true就跳过,第二个是可迭代对象 ~~~ ~~~ from itertools import dropwhile with open('txt.txt') as f: for line in f: print(line) with open('txt.txt') as f: for line in dropwhile(lambda line:line.startswith('#'), f): print(line) ~~~ >[danger] ##### islice 从指定项开始 ~~~ from itertools import islice item = ['a', 'b', 'c', 1, 3] for i in islice(item, 3, None): print(i) ~~~