原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12170958.html
List 遍历
1 l = [1, 2, 3, 4, 5, 6] 2 3 for i in l: 4 print(i) 5 6 for i in range(len(l)): 7 print(i, l[i])
Tuple 遍历
1 tup = (1, 2, 3, 1, 2, 3) 2 3 for i in tup: 4 print(i) 5 6 for i in range(len(tup)): 7 print(i, tup[i])
Set 遍历
1 s = {4, 2, 3, 1, 5} 2 for i in s: 3 print(i)
Dict 遍历
1 data = {"username": "HelloWorld", "age": 22, "role": "student"} 2 3 # 直接遍历字典获取值,根据键取值 4 for key in data: 5 print(key, data[key]) 6 7 # 利用items方法获取键值,速度很慢,尽量不用 8 for key, value in data.items(): 9 print(key, value) 10 11 # 利用keys获取键,根据键取值 12 for key in data.keys(): 13 print(key, data[key]) 14 15 # 利用values获取值,但是无法获取对应的键 16 for value in data.values(): 17 print(value)
Reference
https://www.runoob.com/python3/python3-list.html
https://www.runoob.com/python3/python3-tuple.html