python 遍历

python中遍历的方法有哪些

养鱼的猫咪
185
2021-03-18 11:34:41
栏目: 编程语言

python中实现遍历的方法:1.使用iter()函数遍历;2.使用enumerate()函数遍历;3.使用range()和len()函数遍历;

python中遍历的方法有哪些

python中实现遍历的方法有以下几种

1.使用iter()函数遍历


cities = ["Guangzhou","Beijing","Shanghai","Nanjing"]


for city in iter(cities):

print(city)


输出结果为:


Guangzhou

Beijing

Shanghai

Nanjing


2.使用enumerate()函数遍历


cities = ["Guangzhou","Beijing","Shanghai","Nanjing"]


for i,city in enumerate(cities):

print(i+1,city)


输出结果为:


1 Guangzhou

2 Beijing

3 Shanghai

4 Nanjing


3.使用range()和len()函数遍历


cities = ["Guangzhou","Beijing","Shanghai","Nanjing"]


for i in range(len(cities)):

print(i+1,cities[i])


输出结果为:


1 Guangzhou

2 Beijing

3 Shanghai

4 Nanjing



0
看了该问题的人还看了