def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line=next(f)
if line is None:
break
print(line,end='')
except StopIteration:
pass
#test case items=[1,2,3] it=iter(items) next(it) next(it) next(it)
class Node:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.fromat(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
#将迭代请求传递给内部的_children属性
return iter(self._children)
#test case
if __name='__main__':
root=Node(0)
child1=Node(1)
child2=Nide(2)
root.add_child(child1)
root.add_child(child2)
for ch in root:
print(ch)
a=[1,2,3,4]
for x in reversed(a):
print(x) #4 3 2 1
f=open('somefile')
for line in reversed(list(f)):
print(line,end='')
#test case
for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
class Countdown:
def __init__(self,start):
self.start=start
#常规迭代
def __iter__(self):
n=self.start
while n > 0:
yield n
n -= 1
#反向迭代
def __reversed__(self):
n=1
while n <= self.start:
yield n
n +=1
with open('/etc/passwd') as f:
for line in f:
print(line,end='')
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line:line.startwith('#'),f):
print(line,end='')
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_types):
yield from flatten(x)
else:
yield x
#test case items=[1,2,[3,4,[5,6],7],8] for x in flatten(items): print(x)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有