python中的for循环

一、for循环概要:

  1. for循环是一个通用序列迭代器,可遍历任何有序的序列对象内的元素,包括字符串、列表、元组、其他内置可迭代对象。
  2. 一般格式:
 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!"
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值