一、for循环概要:
- for循环是一个通用序列迭代器,可遍历任何有序的序列对象内的元素,包括字符串、列表、元组、其他内置可迭代对象。
- 一般格式:
for <target> in <object>:
<statements>
if <test> :break
if <test1>:continue
else:
<statement> ``
二、for循环应用举例:
1、遍历序列元素:
for x in ['spam','eggs','ham']:
print x,
print ""
sum = 0
for y in [1,2,3,4]:
sum += y
print "sum=",sum
2、遍历字符串:
S = "lumberjack"
T = ("and","I'm","okay")
for x in S:
print x,
print ''
for y in T:
print y,
print ''
3、遍历元组:
U = [(1,2),(3,4),(5,6)]
for (a,b) in U:
print a,b
for a,b,c in [(1,2,3),(4,5,6)]:
print a,b,c
4、遍历字典:
D = {'A':1,'B':2,'C':3,'D':4}
for key in D:
print key,'->',D[key]
print type(D.items())
print D.items() #[('A', 1), ('C', 3), ('B', 2), ('D', 4)]
print list(D.items()) #[('A', 1), ('C', 3), ('B', 2), ('D', 4)]
for key,value in D.items():
print key,'->',value
5、for嵌套:从items中查找是否存在tests中的元素
items = ['aaa',111,(4,5),2.01]
tests = [(4,5),3.14]
for key in tests:
for item in items:
if key == item:
print key,'was found!'
break
else:
print key,"not found!"