Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1342378
  • 博文数量: 243
  • 博客积分: 888
  • 博客等级: 准尉
  • 技术积分: 2955
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-05 14:33
个人简介

漫漫长路,其修远兮!

文章分类

全部博文(243)

文章存档

2017年(2)

2016年(22)

2015年(32)

2014年(57)

2013年(107)

2012年(23)

分类: Python/Ruby

2014-10-09 18:31:54

一.条件判断
if   expression:
    xxxx
else:
    xxxx

if  expression1:
  xxxx
elif expression2:
  xxxx
else:
  xxxx

if user.cmd in ('create', 'delete', 'update'):
   action = '%s item' % user.cmd
else:
   action = 'invalid choice... try again!'

二.循环
while (count < 9):
   print 'the index is:', count
   count += 1

for 循环迭代不同的序列对象. 样例将涵盖字符串, 列表, 以及元组
for eachLetter in 'Names':
   print 'current letter:', eachLetter
序列的三种迭代方式
1.通过序列项迭代
nameList = ['Walter', "Nicole", 'Steven', 'Henry']
for eachName in nameList:
   print eachName, "Lim"
2.通过序列索引迭代
nameList = ['Cathy', "Terry", 'Joe', 'Heather','Lucy']
for nameIndex in range(len(nameList)):
   print "Liu,", nameList[nameIndex]
3.使用项和索引迭代
nameList = ['Donn', 'Shirley', 'Ben', 'Janice','David', 'Yen', 'Wendy']
for i, eachLee in enumerate(nameList):
    print "%d %s Lee" % (i+1, eachLee)
与序列相关的内建函数
sorted(), reversed(), enumerate(), zip()

三.迭代器
迭代器就是有一个next()方法的对象,而不是通过索引来计数的,当你或是一个循环机制(例如 for 语句)需要下一个项时, 调用迭代器的 next() 方法就可以获得它. 条目全部取
出后, 会引发一个 StopIteration 异常, 这并不表示错误发生, 只是告诉外部调用者, 迭代完成。
1.序列迭代
myTuple = (123, 'xyz', 45.67)
i = iter(myTuple)
i.next()
123
i.next()
'xyz'
i.next()
45.67
i.next()
Traceback (most recent call last):
File "", line 1, in ?
StopIteration

字典迭代
for eachKey in myDict.keys() 可以缩写为 for eachKey in myDict
Python 还引进了三个新的内建字典方法来定义迭代: myDict.iterkeys() (通过 keys 迭代), myDict.itervalues() (通过 values 迭代), 以及 myDicit.iteritems() (通过 key/value 对来迭代). 注意, in 操作符也可以用于检查字典的 key 是否存在 , 之前的布尔表达式myDict.has_key(anyKey) 可以被简写为 anyKey in myDict

文件迭代
myFile = open('config-win.txt')
for eachLine in myFile:
  print eachLine, # comma suppresses extra \n
myFile.close()









阅读(965) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~