python学习小结1:for循环控制语句

用一个列表来确定for循环的范围

>>> x = [0,1,2,3,4]
>>> for i in x:
    print i,

    
0 1 2 3 4

 循环一个字符串

>>> x = 'python'
>>> for i in x:
    print i,

    
p y t h o n

 元组for循环

>>> x = [('http','https'),('java','python')]
>>> for (a,b) in x:
    print (a,b)

    
('http', 'https')
('java', 'python')

 迭代器

# 文件迭代器,读取文件的最佳实践
>>> for line in open('test.txt'):
    print line.upper()

    
HELLO,WORD!

# 字典迭代器
>>> testDict = {'name':'ethon','aender':'male'}
>>> for key in testDict:
    print key + ':' + testDict[key]

    
aender:male
name:ethon

 迭代协议:有一些函数可以在支持迭代协议的对象上运行

>>> testList = [9,8,7,6,5]
>>> print sorted(testList)
[5, 6, 7, 8, 9]
>>> print sum(testList)
35
>>> print any(testList)
True
>>> print list(open('test.txt'))
['Hello,word!']
>>> print tuple(open('test.txt'))
('Hello,word!',)
# 元组、列表的构造函数以及join都可以对支持迭代协议的对象操作 >>> print ('--').join(open('test.txt')) Hello,word!

 使用range函数来产生循环的范围

>>> for i in range(5):
    print str(i)+ 'is the current value'

    
0 is the current value
1 is the current value
2 is the current value
3 is the current value
4 is the current value

zip拉链:使用zip函数可以把两个列表合并起来,成为一个元组的列表。

>>> L1 = [1,3,5,7]
>>> L2 = [2,4,6,8]
>>> print zip(L1,L2)
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>> for (a,b) in  zip(L1,L2):
    print (a,b)

    
(1, 2)
(3, 4)
(5, 6)
(7, 8)

 可变嵌套循环

ns = int(raw_input("How many lines of starts do you want? "))
st = int(raw_input("How many start do you want? "))
for line in range(0,ns): # 外循环
    for star in range(0,st): # 内循环
        print "*",
    print

-------------------------------------------
How many lines of starts do you want? 3
How many start do you want? 5
* * * * *
* * * * *
* * * * *

 

posted on 2015-01-26 11:23 Ethon 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wakey/p/4249810.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值