通过collections模块的Iterable类型判断对象是否可迭代:
>>> from collections import Iterable >>> isinstance('abc', Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False >>>
把列表变成索引-元素对, enumerate 为Python内置函数:
>>> str=['a', 'b', 'c'] >>> for i,v in enumerate(str): ... print(i,v) ... 0 a 1 b 2 c >>>
引用元组列表:
>>> t=[(1,2), (3,4), (5,6)] >>> for m,n in t: ... print(m,n) ... 1 2 3 4 5 6 >>>