>>> for elem in [1,2,3]: ... print(elem) ... 1 2 3
>>> for i in ("zhang", "san", 30):
... print(i)
...
zhang
san
30 >>> for c in "abc": ... print(c) ... a b c
>>> for i in {"a","b","c"}:
... print(i)
...
b
a
c >>> for k in {"age":10, "name":"wang"}:
... print(k)
...
age
name >>> for line in open("requirement.txt"):
... print(line, end="")
...
Fabric==1.12.0
Markdown==2.6.7 >>> class MyRange: ... def init(self, num): ... self.num = num ... >>> for i in MyRange(10): ... print(i) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'MyRange' object is not iterable
>>> x = [1,2,3] >>> its = x.iter() # x有此方法,说明列表是可迭代对象 >>> its <list_iterator object at 0x100f32198> >>> its.next() # its有此方法,说明its是迭代器 1 >>> its.next() 2 >>> its.next() 3 >>> its.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
class MyRange: def init(self, num): self.i = 0 self.num = num def iter(self): return self def next(self): if self.i < self.num: i = self.i self.i += 1 return i else: # 达到某个条件时必须抛出此异常,否则会无止境地迭代下去 raise StopIteration()
for i in MyRange(3): print(i) #输出 0 1 2
有没有发现,自定义的 MyRange 功能和内建函数 range很相似。for 循环本质是不断地调用迭代器的next方法,直到有 StopIteration 异常为止,所以任何可迭代对象都可以作用在for循环中。
以上就是详解Python中for循环的工作原理的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于详解Python中for循环的工作原理的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did81951