Python: 遍歷

======================遍歷列表========================
# 直接遍歷list:spa

for elem in list:
     pass

 

# 經過索引獲取code

for i in range(len(list)):
     elem = list[i]
     pass

 

# 基於enumerate()遍歷blog

for i, elem in enumerate(list):
     pass

 

# 基於iter()遍歷索引

listIter = iter(list)
while True:
     try:
          elem = listIter.next()
          # ....
     expect StopIteration, ex:
          // NOOP

 

=====================遍歷dict==========================
# 經過key遍歷get

for key in dict.keys():
     value = dict.get(key)
     pass

 

# 直接遍歷,本質是先轉換成 (key,value)的listit

for key,value in dict.items():
     pass

 

# iteritems() 返回值是 items的迭代器io

for key,value in dict.iteritems():
     pass
相關文章
相關標籤/搜索