foreach循环
-
python的list是一组可变变量的指针,有长度和容量区别,会自动调整容量,类似于golang的机制
-
a=[0,1,2] b=[-1]*6 i=0 #姑且称为前者,后者 #foreach 前者可以在循环过程中变化 for b[i] in a: i+=2 print(b)#[0, -1, 1, -1, 2, -1]
-
a=[ [1,2,3], [4,5,6], [7,8,9] ] b=[-1]*3 i=0 #foreach,后者是可遍历对象对象。其实是一个地址拷贝,只会在第一次时候拷贝个地址。以后就算是a[i]引用到其它地方了,也不影响原来的拷贝。这里后者始终是[1, 2, 3] for b[i] in a[i]:#无法得到b=[1,5,9],证明foreach的后者始终是首次拷贝地址 print(a[i])#循环过程可以正常操作a[i] i+=1 print(b) # [1, 2, 3] # [4, 5, 6] # [7, 8, 9] # [1, 2, 3]
-
a = [0, 1, 2, 3, 4] b = [] #foreach 首次就形成一个内置的遍历变量index,每次严格只会index++,遍历的结束条件和原拷贝的长度有关 for i in a: b.append(i) a.pop() print(b) # [0, 1, 2] print(a) # [0, 1]
-
a = [0, 1, 2, 3, 4, 5] b = [] #foreach,每次循环index不会管a是否变化,只是无脑+1。每次如果原拷贝a的值刷新了,在新原拷贝的值里面选出i=a[index]。注意是值刷新,原拷贝本身的地址没有刷新 for i in a: b.append(i) a.pop(0) print(b) # [0, 2, 4] print(a) # [3, 4, 5]
-
a = [ [1], [4, 5], [7, 8, 9] ] b = [-1] * 3 i = 0 #可见是原拷贝相当于指针常量,未曾变化(即未出现b=[1,5,9]的意外结果) for b[i] in a[i]: i += 1 print(b)#[1, -1, -1]
-
a = [ [11, 12, 13, 14, 15, 16, 17, 18, 19], [4, 5], [7, 8, 9] ] c = a[0] b = [-1] * 9 i = 0 #可见在循环过程中,c也指向原拷贝,所以c变化就影响了原拷贝,从而影响了最终的循环次数 for b[i] in a[i]: i += 1 c.pop() print(b) # [11, 12, 13, 14, 15, -1, -1, -1, -1]
-
a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] d = [ [11, 12, 13], [14, 15, 16], [17, 18, 19] ] b = [-1] * 3 i = 0 #可见b的值其实都是原拷贝那边得到的 for b[i] in a[i]: a[i] = d[i] i += 1 print(b) print(a) # [1, 2, 3] # [[11, 12, 13], [14, 15, 16], [17, 18, 19]]
for循环
-
n = 5 b = [] c = [] #可以在for循环中改变前者i,但是每次循环时它会自动重新赋值,以同步到内置的index变量 for i in range(n): print(i) b.append(i) i += 10 c.append(i) print(b) print(c) # 0 # 1 # 2 # 3 # 4 # [0, 1, 2, 3, 4] # [10, 11, 12, 13, 14]
-
n=9 b=[] #for循环,后者如果是数字,就是按值拷贝,可见循环中改变了n的值,但是不影响原拷贝 for i in range(n): b.append(i) n-=1 print(b) print(n) # [0, 1, 2, 3, 4, 5, 6, 7, 8] # 0
-
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [] #后者是引用型变量也一样,都是先首次仅来一次原拷贝 for i in range(len(a)): b.append(i) a.pop() #a[i]=666#!谨慎当for遍历数组时,修改数组长度和用索引查改数组元素,两者一起使用很可能会出逻辑错误 print(b) print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # []
-
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [] c = [] #for循环时,前者后后者一起改变的例子 for i in range(len(a)): a.pop() i += 80 b.append(i) print(b) print(a) # [80, 81, 82, 83, 84, 85, 86, 87, 88, 89] # []