Python for循环是基于迭代器的“ for-each”循环。每次迭代开始时都会重新分配迭代变量。换句话说,以下循环:
In [15]: nums = 1,2,5,8In [16]: for num in nums: ...: print(num) ...:1258
等效于:
In [17]: it = iter(nums) ...: while True: ...: try: ...: num = next(it) ...: except StopIteration: ...: break ...: print(num) ...:1258
同样,以下循环是等效的:
In [19]: for num in nums: ...: print("num:", num) ...: num += 1 ...: print("num + 1:", num) ...: ...:num: 1num + 1: 2num: 2num + 1: 3num: 5num + 1: 6num: 8num + 1: 9In [20]: it = iter(nums) ...: while True: ...: try: ...: num = next(it) ...: except StopIteration: ...: break ...: print("num:", num) ...: num += 1 ...: print("num + 1:", num) ...:num: 1num + 1: 2num: 2num + 1: 3num: 5num + 1: 6num: 8num + 1: 9
请注意,C样式的for循环在Python中不存在,但是您始终可以编写while循环(c样式的for循环本质上是while循环的语法糖):
for(int i = 0; i < n; i++){ // do stuff}
等效于:
i = 0while i < n: # do stuff i += 1
请注意,不同之处在于,在这种情况下,迭代 取决于i
# do stuff,修改的任何内容
i都会影响迭代,而在前一种情况下,迭代取决于
迭代器 。注意,如果我们确实修改了迭代器,则迭代会受到影响:
In [25]: it = iter(nums) # give us an iterator ...: for num in it: ...: print(num) ...: junk = next(it) # modifying the iterator by taking next value ...: ...:15
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)