xyzjr 发表于 2018-8-12 11:30:09

Python---迭代

# 迭代  
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)
  
# 在Python中,迭代是通过for ... in来完成的,而很多语言比如C或者Java,迭代list是通过下标完成的
  
# Python的for循环抽象程度高,因为python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上
  

  
# 迭代dict
  
# 因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样
  
# 默认情况下,dict迭代的是key
  
# 如果要迭代value,可以用for value in d.values()
  
# 如果要同时迭代key和value,可以用for k, v in d.items()
  

  
# 通过collection模块的Iterable类型判断一个对象是可迭代对象
  
from collections import Iterable
  

  
d = {'a': 1, 'b': 2, 'c': 3}
  

  
print('迭代key')
  
for key in d:
  
    print(key)
  

  
print('迭代value')
  
for value in d.values():
  
    print(value)
  

  
print('迭代key&value')
  
for k, v in d.items():
  
    print(k, v)
  

  
# 迭代字符串
  
print('迭代字符串')
  
for ch in 'ABC':
  
    print(ch)
  

  
# str是否可迭代
  
print(isinstance('abc', Iterable))
  
# list是否可迭代
  
print(isinstance(, Iterable))
  
# 整数是否可迭代
  
print(isinstance(123, Iterable))
  

  
# 使用Python内置的enumerate函数把一个list变成索引-元素对,可以在for循环中同时迭代索引和元素本身
  
for i, value in enumerate(['A', 'B', 'C']):
  
    print(i, value)
页: [1]
查看完整版本: Python---迭代