#iter and generator
with open("somefile.txt") as f :
try :
while True :
line = next(f)
print (line)
except StopIteration:
print ("all is ok !")
############################
with open("somefile.txt") as f :
while True :
line = next(f,"GuoqiLiu")###default
print (line,end="")
if line is "GuoqiLiu" :
break
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
class Node :
def __init__(self,value):
self._value = value
self._children = []
def __repr__(self) :
return 'Node({!r})'.format(self._value)
def add_child(self,node) :
self._children.append(node)
def __iter__(self) :
return iter(self._children)
def depth_first(self) :
print ("t++",self)
yield self
for c in self :
yield from c.depth_first()####说明:yield from iterable本质上等于for item in iterable: yield item的缩写版
#Example
if __name__ == "__main__" :
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
#child1.depth_first()
for ch in root.depth_first():
print (ch)
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
a = [1,2,3,4]
r = reversed(a)
#list(r)
#__reversed__() 实现自定义类的反向迭代
class Countdown :
def __init__(self,start):
self.start = start
#Forward iterator
def __iter__(self) :
n = self.start
while n>0:
yield n
n -= 1
#Reverse iterator
def __reversed__(self) :
n = 1
while n<= self.start :
yield n
n += 1
a = Countdown(5)
for i in iter(a) :
print ("iter:",i)
####$$$$$$$$$$$$$$$$$$$$$$###################
for i in reversed(a) :
print ("reversed:",i)
###切片
import itertools
for x in itertools.islice(iter(a),2,4) :######### itertools.islice(iter(a),2,None)##余下所有的元素
print ("slice",x)
##output:
iter: 5
iter: 4
iter: 3
iter: 2
iter: 1
reversed: 1
reversed: 2
reversed: 3
reversed: 4
reversed: 5
slice 3
slice 2
#######################################
#跳过所有的注释行
"""
from itertools import dropwhile
with open ('/etc/passwd') as f :
for line in dropwhile(lambda line: line.startswith('#'),f):
print (line)
"""
#zip
data = [(1,2),(3,4)]
for n,(x,y) in enumerate(data) :
print (n,"++>>>",(x,y))
a = [1,2,3]
b = ['x','y','z','t']
for i in zip(a,b) :
print(i)
#zip则是以最短的那个为准,而itertools.zip_longest()则是以最长的为准##Note:
from itertools import zip_longest
for i in zip_longest(a,b) :
print (i)
for i in zip_longest(a,b,fillvalue=0) :
print (i)
#扁平化处理嵌套型序列
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):
for i in flatten(x) :
yield i
#yield from flatten(x)##如果想编写生成器来把其他生成器当子例程调用yield from 是一个不错的选择。如果不这么用,就需要编写有额外for循环的代码
else:
yield x
items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)
items = ['Dave', 'Paula', ['Thomas', 'Lewis']]
for x in flatten(items):
print(x)