方法:首先創(chuàng)建列表(“stus = ['孫悟空','豬八戒','蜘蛛精']”),然后通過for循環(huán)遍歷列表即可(“for i in stus:print(i)”)。
遍歷列表 : 輸出所有元素
依次遍歷列表
效果圖:
代碼:
# 創(chuàng)建列表 stus = ['孫悟空','豬八戒','沙和尚','唐僧','白骨精','蜘蛛精'] # 依次遍歷列表 print(stus[0]) print(stus[1]) print(stus[2]) print(stus[3])
通過while循環(huán)遍歷列表
效果圖:
代碼:
# 創(chuàng)建列表 stus = ['孫悟空','豬八戒','沙和尚','唐僧','白骨精','蜘蛛精'] # 通過while循環(huán)遍歷列表 i = 0 while i < len(stus): print(stus[i]) i += 1
通過for循環(huán)遍歷列表 最好的遍歷方法
效果圖:
代碼:
# 創(chuàng)建列表 stus = ['孫悟空','豬八戒','沙和尚','唐僧','白骨精','蜘蛛精'] # 通過for循環(huán)遍歷列表 for i in stus: print(i)
推薦教程:《python教程》