2.4字串,列表,元祖,字典遍歷——非常重要的操作
阿新 • • 發佈:2018-12-27
遍歷操作:基本用的都是 for ... in ....操作
注意,重要的都在末尾!
1字串的遍歷:
>>> a_str = "hello itcast"
>>> for char in a_str:
... print(char,end=' ')
...
h e l l o i t c a s t
2:列表遍歷
>>> a_list = [1, 2, 3, 4, 5] >>> for num in a_list: ... print(num,end=' ') ... 1 2 3 4 5
3:元祖遍歷
>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
... print(num,end=" ")
1 2 3 4 5
這三個因為資料結構都是單一型的,而且結構相同!所以大家應該發現了,遍歷結構是一樣的!
4:字典的遍歷:假設字典dic={"name":"fu","id":666},遍歷操作和剛剛的字典基本操作有關係!
遍歷鍵:for key in dic.keys():
遍歷值:for value in dic.values():
以上返回的都是單一值!
遍歷項:for item in dic.items():返回的是元祖型別的鍵值對,上一篇介紹過dic.items()方法返回的是包含所有(鍵,值)元祖的列表!本質還是列表!所以結果就是每個項!
上邊的返回元祖型別的資料!使用不方便!
如果想要單一的訪問鍵和值!方法:for key,value in dic.items()
5帶索引值的遍歷~enumerate()
>>> chars = ['a', 'b', 'c', 'd'] >>> for i, chr in enumerate(chars): ... print i, chr ... 0 a 1 b 2 c 3 d