Python: 遍历

======================遍历列表========================
# 直接遍历list:

for elem in list:
     pass

 

# 通过索引获取

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

 

# 基于enumerate()遍历

for i, elem in enumerate(list):
     pass

 

# 基于iter()遍历

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

 

=====================遍历dict==========================
# 通过key遍历

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

 

# 直接遍历,本质是先转换成 (key,value)的list

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

 

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

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

 

posted @ 2018-09-05 00:17  乐享程序员  阅读(507)  评论(0编辑  收藏  举报