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