http://anandology.com/python-practice-book/iterators.html Problem 1: Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. :: >>> it = reverse_iter([1, 2, 3, 4]) >>> it.next() 4 >>>…
迭代 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration). Python里使用for...in来迭代. 常用可迭代对象有list.tuple.dict.字符串等.示例: list: for x in [1,2]: print(x) for x,y in [(1,2),(3,4)]: print(x,y) 输出: 1 2 1 2 3 4 上面的for循环里,同时引用了两个变量,在Python里是很常见的. tuple:…
1.手动遍历迭代器 使用next函数,并捕获StopIteration异常. def manual_iter(): with open('./test.py') as f: try: while True: line = next(f) print line except StopIteration: pass next函数也可以指定值来标记结尾 def manual_iter(): with open('./test.py') as f: try: while True: line = nex…
列表生成式 列表生成式的操作顺序: 1.先依次来读取元素 for x 2.对元素进行操作 x*x 3.赋予变量 Eg.列表生成式方式一 a = [x*x for x in range(10)] print(a) >>>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Eg.列表生成式方式二 def f(n): return n*n a = [f(x) for x in range(10)] print(a) >>>[0, 1, 4, 9, 16,…