条件和循环

2016-04-08  本文已影响12人  无愠无殇

多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)

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

else语句
----while-else ,for-else,只有while,for正常执行完,
----才执行else语句,当执行break时,跳过else语句

Iterators 迭代器
----具备迭代的类型:1.序列。2.字典。3.文件
----创建迭代器:对象->iter(obj)/ 类->实现 iter()、next()方法

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
上一篇 下一篇

猜你喜欢

热点阅读