迭代--Iteration

#python的for循环可用于任何可迭代对象,如:list,tuple,dict,字符串
L1=[1,2,'wxy','gjh']

for l in L1:
print('list迭代:{}'.format(l))

#对list的下标循环操作,Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身
for i,value in enumerate(L1):
print(i,value)

T1=(3,4,5,6)

for t in T1:
print('tuple迭代:{}'.format(t))

str='hellowxy'

for s in str:
print('str迭代:{}'.format(s))

D1={'wxy':90,'gjh':73,'hmm':65}

#迭代dict的key
for dkey in D1:
print('dict的迭代默认为迭代key:{}'.format(dkey))

#迭代value
for dvalue in D1.values():
print('迭代value:{}'.format(dvalue))

#key和value一起迭代
for dkey,dvalue in D1.items():
print('迭代key和value:{0}-->{1}'.format(dkey,dvalue))

#判断是否为可迭代对象,方法是通过collections模块的Iterable类型判断
from collections import Iterable

#isinstance用法:http://www.cnblogs.com/sweet521/p/3976634.html
print(isinstance(123,Iterable))
print(isinstance([1,2,3],Iterable))
原文地址:https://www.cnblogs.com/wangxy92/p/7478858.html