条件和循环
2016-04-08 本文已影响12人
无愠无殇
- if
- else
- elif
多elif 判断的优雅解决方案
cmd = raw_input('input your command')
msgs = {'create': 'create item',
'delete': 'delete item',
'update': 'update item'}
default = 'invalid choice ... try again'
action = msgs.get(cmd, default)
-
‘三元操作符’ X if C else Y
C 条件表达式 -
while
-
for
1.通过序列项迭代
nameList = ['zhangsan','lisi','wanger']
for eachName in nameList:
print eachName
2.通过序列索引迭代
nameList = ['zhangsan','lisi','wanger']
for i in range(len(nameList)):
print nameList[i]
3.使用项和索引迭代
nameList = ['zhangsan','lisi','wanger']
for i, eachName in enumerate(nameList):
print '%d %s' % (i+1,eachName)
4.用于迭代器类型 (文件、序列类型)
for eachLine in open('/etc/passwd'):
print eachLine
- break ------用于跳出for while循环
- continue ----用于启动循环的下一次迭代,忽略剩余的语句,回到循环的顶点
- pass ------NOP,定结构
else语句
----while-else ,for-else,只有while,for正常执行完,
----才执行else语句,当执行break时,跳过else语句
Iterators 迭代器
----具备迭代的类型:1.序列。2.字典。3.文件
----创建迭代器:对象->iter(obj)/ 类->实现 iter()、next()方法
-
列表解析
----[x ** 2 for x in range(6) if x % 2]
----不足:必要生成所有的数据,用以创建整个列表 -
生成器表达式
----懒惰的列表解析、每次计算一个条目,都是yield出来
rows = [1,2,3,17]
def cols():
yield 56
yield 2
yield 1
x = ((i,j) for i in rows for j in cols())
for pair in x:
print pair