python学习小结1:for循环控制语句
来源:互联网 发布:程序员地中海 编辑:程序博客网 时间:2024/04/30 07:12
用一个列表来确定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:malename: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 value1 is the current value2 is the current value3 is the current value4 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
* * * * *
* * * * *
* * * * *
0 0
- python学习小结1:for循环控制语句
- 关于Python中的for循环控制语句
- 关于Python中的for循环控制语句
- python循环控制语句(for)
- 关于Python中的for循环控制语句
- 关于Python中的for循环控制语句
- 关于Python中的for循环控制语句
- Python学习流程控制 if 语句、while语句、for..in...循环
- for循环控制语句
- python学习6-流程控制-for循环
- python 学习(六) for 循环语句
- Python学习 for循环语句的使用
- Python for 循环语句
- Python--for 循环语句
- Python for 循环语句
- Python for 循环语句
- Python for 循环语句
- Python中的for循环控制语句-常见误区
- 第五周 项目1-建立顺序栈算法库
- 第五周项目1-建立顺序栈算法库
- Java动态代理的理解(知乎转发)
- Fiddler 手机抓包
- 哈士奇与阿拉斯加的区别!
- python学习小结1:for循环控制语句
- python学习小结2:if和while控制语句
- 搜索引擎选择: Elasticsearch与Solr
- 第5周 项目5-后缀式表达
- python学习小结3:函数
- python学习小结4:类
- Kettle使用介绍
- 机器学习实战
- python学习小结5:封装、继承、多态