要点1:分清楚内外循环
左起为外循环,右起为内循环:
eg1:
print([j for i in range(0, 10) for j in range(0, 2)])
list1 = []
for i in range(0, 10):
for j in range(0, 2):
list1.append(j)
print(list1)
结果:
eg2:
print([i for i in range(0, 10) for j in range(0, 2)])
list2 = []
for i in range(0, 10):
for j in range(0, 2):
list2.append(i)
print(list2)
结果:
要点2:带if判断的for循环嵌套
eg3:
print([i for i in range(0, 10) for j in range(0, 2) if i not in [0, 1, 2, 3, 4]])
list2 = []
for i in range(0, 10):
for j in range(0, 2):
if i not in [0, 1, 2, 3, 4]:
list2.append(i)
print(list2)
结果: