python入门语法教程:循环嵌套
嵌套循环和if语句的嵌套原理相似,就是在一个循环体内嵌套另外一个循环体。不同的是循环嵌套可以采用for-for嵌套、for-while嵌套、while-for嵌套、以及while-while嵌套四种形式。
1. for-for嵌套
它的形式为:
1234 |
for i
in range
(n):
for j
in range
(m):
循环体
2
循环体
1 |
举个例子:
我们定义两个列表(一种存储数据的容器)。
list_first = [1,2,3,4,5,6,7,8,9]
list_second = [2,4,8,10,12,20]
我们要找到两个列表中相同的数据并打印出来。
代码如下:
123456 |
list_first
= [
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
list_second
= [
2
,
4
,
8
,
10
,
12
,
20
]
for i
in list_first:
for j
in list_second:
if i
=
= j:
print
(i) |
输出结果为:
123 |
2
4
8 |
2. for-while嵌套
它的形式为:
1234 | for 变量
in 对象:
while 条件:
循环体
2
循环体
1 |
举个例子:
index = [1,32,77,121,150]
遍历输出index列表中的值,对于小于100的数,把它每次加上10,直到大于100后再输出。
代码如下:
12345 |
index
= [
1
,
32
,
77
,
121
]
for i
in index:
#遍历index
while i |