python中实现遍历的方法:1.使用iter()函数遍历;2.使用enumerate()函数遍历;3.使用range()和len()函数遍历;
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